﻿using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Diagnostics;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.ServiceModel;
using System.ComponentModel;
using System.Globalization;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;

using PickGold.Generic;
using PickGold.Handler;
using PickGold.Attributes;

namespace PickGold
{
	/// <summary>
	/// Reflection
	/// </summary>
	public static class Reflector
	{
		#region inner class

		#region class _ : RealProxy

		class _ : RealProxy
		{
			class O : MarshalByRefObject { public int o;}

			public MethodInfo FieldSetter;

			public MethodInfo FieldGetter;

			public MethodInfo TypeGetter;

			public string GetHashCodeString;

			public string ToStringString;

			public _()
				: base(typeof(O))
			{
				var o = this.GetTransparentProxy() as O;
				o.o = o.o + 1;
				TypeGetter = new Func<Type>(this.GetType).Method;
				GetHashCodeString = new Func<int>(this.GetHashCode).Method.ToString();
				ToStringString = new Func<string>(this.ToString).Method.ToString();
			}

			public override IMessage Invoke(IMessage msg)
			{
				var mcm = msg as IMethodCallMessage;
				if (mcm.Args[2] == null)
					this.FieldGetter = mcm.MethodBase as MethodInfo;
				else
					this.FieldSetter = mcm.MethodBase as MethodInfo;
				return new ReturnMessage(null, mcm.Args, mcm.ArgCount, mcm.LogicalCallContext, mcm);
			}
		}

		#endregion

		static class CustomAttributeExtensions//这是一个对基础程序集内部隐藏的类方法反射，应该不会存在找不到的情况。
		{
			public static Func<MemberInfo, Type, IEnumerable<Attribute>> GetCustomAttributes_MemberInfo_Type;

			public static Type Origin//这是一个对基础程序集内部隐藏的类方法反射，应该不会存在找不到的情况。
			{
				get
				{
					var n = typeof(CustomAttributeExtensions).Name;
					var v = Type.GetType(typeof(MemberInfo).Namespace + "." + n);
					if (v != null)
						return v;

					foreach (var t in typeof(MemberInfo).Assembly.GetTypes())
					{
						if (t.Name == n)
							return t;
					}
					return null;//throw new NotImplementedException("Type " + n + " Not implemented in " + typeof(MemberInfo).Assembly.GetName().Name);//这是一个对基础程序集内部隐藏的类方法反射，应该不会存在找不到的情况。
				}
			}

			public static IEnumerable<Attribute> GetCustomAttributes(MemberInfo member, Type attributeType)
			{
				if (GetCustomAttributes_MemberInfo_Type == null)
				{
					if (Origin != null)
					{
						var h = Delegate.CreateDelegate(typeof(Func<MemberInfo, Type, IEnumerable<Attribute>>), Origin, MethodBase.GetCurrentMethod().Name) as Func<MemberInfo, Type, IEnumerable<Attribute>>;
						GetCustomAttributes_MemberInfo_Type = h;
					}
					else
					{
						var h = new Func<MemberInfo, Type, IEnumerable<Attribute>>(GetCustomAttributes);
						GetCustomAttributes_MemberInfo_Type = h;
					}
				}
				if (GetCustomAttributes_MemberInfo_Type.Method.DeclaringType.FullName != typeof(CustomAttributeExtensions).FullName)
					return GetCustomAttributes_MemberInfo_Type(member, attributeType);

				// throw new NotSupportedException(h.Method.DeclaringType.Name + "::" + h.Method + ", Not supported");//这是一个对基础程序集内部隐藏的类方法反射，应该不会存在找不到的情况。
				if (attributeType == null)
					return member.GetCustomAttributes(true) as Attribute[];

				return member.GetCustomAttributes(attributeType, true) as Attribute[];
			}

			private static IEnumerable GetAttributes(MemberInfo member, Type attributeType)
			{
				var t = member as Type;
				var m = member as MethodBase;
				var p = member as PropertyInfo;
				var f = member as FieldInfo;
				if (t == null)
				{
					var cs = attributeType == null ? member.GetCustomAttributes(false) : member.GetCustomAttributes(attributeType, false);
					foreach (var c in cs)
						yield return c as Attribute;

					if (p != null)
					{
						m = p.GetGetMethod();
						if (m == null)
							m = p.GetSetMethod();
					}
					if ((m != null && m.IsStatic) ||
						(f != null && f.IsStatic))
						yield break;

					t = member.DeclaringType;
					foreach (var i in t.GetInterfaces())
					{
						var ms = i.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
						foreach (var mm in ms)
						{
							if (mm + "" == member + "")
							{
								var vs = GetAttributes(mm, attributeType);
								foreach (var c in vs)
									yield return c;
							}
						}
					}
					for (; ; )
					{
						t = t.BaseType;
						if (t == null)
							break;

						var ms = t.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
						foreach (var mm in ms)
						{
							if (mm + "" == member + "")
							{
								var vs = GetAttributes(mm, attributeType);
								foreach (var c in vs)
									yield return c;
							}
						}
					}
					yield break;
				}

				var os = attributeType == null ? t.GetCustomAttributes(false) : t.GetCustomAttributes(attributeType, false);
				foreach (var c in os)
					yield return c;
				foreach (var ff in t.GetInterfaces())
				{
					var vs = GetAttributes(ff, attributeType);
					foreach (var c in vs)
						yield return c;
				}
				for (; ; )
				{
					t = t.BaseType;
					if (t == null)
						break;

					os = attributeType == null ? t.GetCustomAttributes(false) : t.GetCustomAttributes(attributeType, false);
					foreach (var c in os)
						yield return c;
				}
				//yield break;
			}

			private static IEnumerable<T> GetAttributes<T>(MemberInfo member) where T : Attribute
			{
				foreach (var i in GetAttributes(member, typeof(T)))
					yield return i as T;
			}
		}

		#region public static class Struct<TYPE> where TYPE : struct

		/// <summary/>
		public sealed class Struct<TYPE> : Reflector<TYPE> where TYPE : struct
		{
			private Struct() { }

			/// <summary/>
			public readonly static Nullable<TYPE> Nullable = null;
			/// <summary/>
			public readonly static Nullable<TYPE> DefaultNullable = new Nullable<TYPE>(DefaultValue);
		}

		#endregion

		sealed class _NameValueCollection : NameValueCollection
		{
			private _NameValueCollection() : base(0) { this.IsReadOnly = true; }
			private _NameValueCollection(SerializationInfo info, StreamingContext context) : base(info, context) { this.IsReadOnly = true; }

			public sealed override void Add(string name, string value)
			{
				throw new NotSupportedException();
			}

			public sealed override void Set(string name, string value)
			{
				throw new NotSupportedException();
				//base.Set(name, value);
			}

			public static readonly NameValueCollection Value = new _NameValueCollection();
		}

		/// <summary>
		/// 泛型常用类型值
		/// </summary>
		public sealed class Generic<TYPE> : Reflector<TYPE> { private Generic() { } }

		/// <summary>
		/// 泛型常用类型值
		/// </summary>
		public sealed class Generic<KEY, VALUE> : Reflector<KEY, VALUE> { private Generic() { } }

		#endregion

		/// <summary>
		/// 空字符串
		/// </summary>
		public readonly static string NullString = AsciiString.NULL;

		/// <summary>
		/// 空引用数组
		/// </summary>
		public readonly static object[] NullArray = null;

		/// <summary>
		/// 空数组
		/// </summary>
		public readonly static object[] EmptyArray = { };

		/// <summary>
		/// 空对象
		/// </summary>
		public readonly static object Null = null;

		/// <summary>
		/// 空的只读的 NameValueCollection 对象
		/// </summary>
		public static NameValueCollection EmptyNameValues
		{
			get
			{
				return _NameValueCollection.Value;
			}
		}

		/// <summary>
		/// 无限枚举器，可直接造成无限循环，使用应极小心
		/// </summary>
		public static IEnumerable InfiniteEnumerable
		{
			get
			{
				return Reflector<object>.InfiniteEnumerable;
			}
		}
		/// <summary/>
		public static IEnumerable EmptyEnumerable
		{
			get
			{
				return Reflector<object>.EmptyArray;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public readonly static MethodInfo FieldSetter;

		/// <summary>
		/// 
		/// </summary>
		public readonly static MethodInfo FieldGetter;

		/// <summary>
		/// GetType
		/// </summary>
		public readonly static MethodInfo TypeGetter;

		/// <summary>
		/// GetHashCode
		/// </summary>
		public readonly static string GetHashCodeString;

		/// <summary>
		/// ToString
		/// </summary>
		public readonly static string ToStringString;

		/// <summary>
		/// 静态标识符：Assembly::GuidAttribute::Value
		/// </summary>
		public readonly static Guid StaticId;

		/// <summary>
		/// Void
		/// </summary>
		public readonly static Type Void = typeof(void);

		/// <summary>
		/// 返回 Root 目录，如果不存在 Root 目录则返回工作目录
		/// </summary>
		public readonly static string RootDirectory;
		/// <summary>
		/// 返回 Bin 目录，如果不存在 Bin 目录则返回工作目录
		/// </summary>
		public readonly static string BinDirectory;
		/// <summary>
		/// 基础目录，如果目录在 Bin 下则返回父目录，如果目录在 Root 下则返回父目录
		/// </summary>
		public readonly static string HomeDirectory;

		static Reflector()
		{
			var map = AppDomain.CurrentDomain.GetData(typeof(MapPath).FullName) as MapPath;
			GetDirectory(map, AppDomain.CurrentDomain, bin: ref BinDirectory, root: ref RootDirectory, home: ref HomeDirectory);
			if (map != null)
			{
				BinDirectory = GetDirectory(map, BinDirectory);
				RootDirectory = GetDirectory(map, RootDirectory);
				HomeDirectory = GetDirectory(map, HomeDirectory);
			}

			var p = new _();
			FieldSetter = p.FieldSetter;
			FieldGetter = p.FieldGetter;
			TypeGetter = p.TypeGetter;
			GetHashCodeString = p.GetHashCodeString;
			ToStringString = p.ToStringString;
			StaticId = typeof(Reflector).Assembly.GetGuidAttributeValue();
		}

		#region GetDirectory

		/// <summary>
		/// 转换到虚拟路径
		/// </summary>
		/// <param name="map">虚拟路径转换委托，AppDomain.GetData(typeof(MapPath).FullName)</param>
		/// <param name="path">要转换的路径</param>
		/// <returns>转换后的路径</returns>
		public static string GetDirectory(MapPath map, string path)
		{
			if (map == null)
				map = AppDomain.CurrentDomain.GetData(typeof(MapPath).FullName) as MapPath;
			if (map == null)
				return path;

			if (string.IsNullOrWhiteSpace(path))
				return map("~/");

			var p = path.Replace('\\', '/');
			if (!p.StartsWith("~/"))
			{
				var r = map("~/").Replace('\\', '/');
				if (!p.StartsWith(r, StringComparison.OrdinalIgnoreCase))
					return path;

				p = "~/" + path.Substring(r.Length);
			}
			if (p.StartsWith("~/../") || p == "~/..")
			{
				var r = map("~/");
				path = r;
				while (p.StartsWith("~/../") || p == "~/..")
				{
					if (p == "~/..")
						p = "~/";
					else
						p = "~/" + p.Substring(5);// ~/../
					r = Path.GetDirectoryName(path);
					if (!string.IsNullOrWhiteSpace(r))
						path = r;
				}
				if (p != "~/")
					p = Path.Combine(path, p.Substring(2));
				else
					p = path;
				if (path.IndexOf('/') >= 0)//if (Path.DirectorySeparatorChar == '/')
					p = p.Replace('\\', '/');
				else
					p = p.Replace('/', '\\');
				return p;
			}

			p = map(p);
			return p;
		}

		private static string GetDirectory(MapPath map, AppDomain app, ref string bin, ref string root, ref string home)
		{
			if (app == null)
				app = AppDomain.CurrentDomain;
			var path = app.BaseDirectory;
			GetDirectory(map, path, ref bin, ref root, ref home);
			return path;
		}

		// get any path
		private static string GetDirectory(MapPath map, string path, ref string bin, ref string root, ref string home)
		{
			var t = path;
			if (string.IsNullOrWhiteSpace(t))
			{
				if (map == null)
					return GetDirectory(map, AppDomain.CurrentDomain, ref bin, ref root, ref home);

				t = map("~/");
			}

			t = Path.PathSeparator == '/' ? t.Replace('\\', Path.PathSeparator) : t.Replace('/', Path.PathSeparator);
			if (t[t.Length - 1] == Path.PathSeparator)
				t = t.Remove(t.Length - 1);

			home = t;
			if (home.EndsWith(Path.PathSeparator + "bin"))
				home = Path.GetDirectoryName(home);

			bin = Path.Combine(home, "bin");
			if (!Directory.Exists(map != null ? GetDirectory(map, bin) : bin))
				bin = home;

			if (home.EndsWith(Path.PathSeparator + "root"))
				home = Path.GetDirectoryName(home);

			root = Path.Combine(home, "root");
			if (!Directory.Exists(map != null ? GetDirectory(map, root) : root))
				root = home;

			return path;
		}

		/// <summary>
		/// 获取目录，返回 Bin 目录，或 App_Data 目录下的路径；
		/// 此方法不能完全代替 Http 环境下的 HttpServerUtility::MapPath 方法，相对或虚拟目录不能正确转义
		/// </summary>
		/// <param name="map">虚拟路径转换委托，AppDomain.GetData(typeof(MapPath).FullName)</param>
		/// <param name="path">基准目录，如进程目录或程序域基目录</param>
		/// <param name="make">如果返回路径为目录，创建目录</param>
		/// <param name="root">从 Root 目录中返回路径，如果不存在 Root 目录则返回基准目录下的路径</param>
		/// <param name="work">从进程根目录或基目录下返回主工作(App_Data)目录路径，如果为空(Empty)则返回 App_Data 目录，如果前缀为 ~/ 则返回基准目录下路径</param>
		/// <param name="subs">子目录名列表，如果任意元素的前缀为 ~/ 则返回基准目录下路径</param>
		/// <returns>目录路径</returns>
		public static string GetDirectory(MapPath map, string path, bool make, bool root, string work, params string[] subs)
		{
			var t = NullString;
			var r = NullString;
			var h = NullString;
			if (map == null)
				map = AppDomain.CurrentDomain.GetData(typeof(MapPath).FullName) as MapPath;
			GetDirectory(map, path, bin: ref t, root: ref r, home: ref h);
			t = root ? r : h;
			if (work != null)
			{
				if (work.Length > 1 && work[0] == AsciiChar.TILDE && (work[1] == AsciiChar.SLASH || work[1] == AsciiChar.BACKSLASH))// ~/
				{

					t = Path.Combine(path, work.Substring(2));
				}
				else if (work == string.Empty || work[0] == AsciiChar.ASTERISK || work[0] == AsciiChar.QUESTION)
				{
					work = Path.Combine(t, "data");
					if (Directory.Exists(map != null ? GetDirectory(map, work) : work))
						t = work;
					else
						t = Path.Combine(t, "App_Data");
				}
				else
				{
					t = Path.Combine(t, work);
				}
			}
			if (subs == null)
			{
				if (map != null)
					t = GetDirectory(map, t);
				if (make && !Directory.Exists(t))
					Directory.CreateDirectory(t);
				return t;
			}

			var l = subs.Length;
			if (l == 0)
			{
				if (map != null)
					t = GetDirectory(map, t);
				if (make && !Directory.Exists(t))
					Directory.CreateDirectory(t);
				return t;
			}

			if (l == 1)
			{
				work = subs[0];
				if (!string.IsNullOrWhiteSpace(work) && work != ".")
				{
					if (work == "..")
						t = Path.GetDirectoryName(t);
					else if (work.Length > 1 && work[0] == AsciiChar.TILDE && (work[1] == AsciiChar.SLASH || work[1] == AsciiChar.BACKSLASH))// ~/
						t = Path.Combine(path, work.Substring(2));
					else
						t = Path.Combine(t, work);
				}
				if (map != null)
					t = GetDirectory(map, t);
				if (make && !Directory.Exists(t))
					Directory.CreateDirectory(t);
				return t;
			}

			for (var i = 0; i < l; i++)
			{
				work = subs[i];
				if (string.IsNullOrWhiteSpace(work) || work == ".")
					continue;

				if (work == "..")
					t = Path.GetDirectoryName(t);
				else if (work.Length > 1 && work[0] == AsciiChar.TILDE && (work[1] == AsciiChar.SLASH || work[1] == AsciiChar.BACKSLASH))// ~/
					t = Path.Combine(path, work.Substring(2));
				else
					t = Path.Combine(t, work);
			}
			if (map != null)
				t = GetDirectory(map, t);
			if (make && !Directory.Exists(t))
				Directory.CreateDirectory(t);
			return t;
		}

		/// <summary>
		/// 获取目录，返回 Bin 目录，或 App_Data 目录下的路径；
		/// 此方法不能完全代替 Http 环境下的 HttpServerUtility::MapPath 方法，相对或虚拟目录不能正确转义
		/// </summary>
		/// <param name="path">基准目录，如进程目录或程序域基目录</param>
		/// <param name="make">如果返回路径为目录，创建目录</param>
		/// <param name="root">从 Root 目录中返回路径，如果不存在 Root 目录则返回基准目录下的路径</param>
		/// <param name="work">从进程根目录或基目录下返回主工作(App_Data)目录路径，如果为空(Empty)则返回 App_Data 目录，如果前缀为 ~/ 则返回基准目录下路径</param>
		/// <param name="subs">子目录名列表，如果任意元素的前缀为 ~/ 则返回基准目录下路径</param>
		/// <returns>目录路径</returns>
		public static string GetDirectory(string path, bool make, bool root, string work, params string[] subs)
		{
			return GetDirectory(null, path, make, root, work, subs);
		}

		/// <summary>
		/// 获取目录，返回 Bin 目录，或 App_Data 目录下的路径；
		/// 此方法不能完全代替 Http 环境下的 HttpServerUtility::MapPath 方法，相对或虚拟目录不能正确转义
		/// </summary>
		/// <param name="app">应用程序域</param>
		/// <param name="make">如果返回路径为目录，创建目录</param>
		/// <param name="root">从 Root 目录中返回路径，如果不存在 Root 目录则返回基准目录下的路径</param>
		/// <param name="work">从进程根目录或基目录下返回主工作(App_Data)目录路径，如果为空(Empty)则返回 App_Data 目录，如果前缀为 ~/ 则返回基准目录下路径</param>
		/// <param name="subs">子目录名列表，如果任意元素的前缀为 ~/ 则返回基准目录下路径</param>
		/// <returns>目录路径</returns>
		public static string GetDirectory(this AppDomain app, bool make, bool root, string work, params string[] subs)
		{
			return GetDirectory(null, app.BaseDirectory, make, root, work, subs);
		}

		/// <summary>
		/// 获取目录，返回 Bin 目录，或 App_Data 目录下的路径；
		/// 此方法不能完全代替 Http 环境下的 HttpServerUtility::MapPath 方法，相对或虚拟目录不能正确转义
		/// </summary>
		/// <param name="type">类型</param>
		/// <param name="make">如果返回路径为目录，创建目录</param>
		/// <param name="root">从 Root 目录中返回路径，如果不存在 Root 目录则返回基准目录下的路径</param>
		/// <param name="work">从进程根目录或基目录下返回主工作(App_Data)目录路径，如果为空(Empty)则返回 App_Data 目录，如果前缀为 ~/ 则返回基准目录下路径</param>
		/// <param name="subs">子目录名列表，如果任意元素的前缀为 ~/ 则返回基准目录下路径</param>
		/// <returns>目录路径</returns>
		public static string GetDirectory(this Type type, bool make, bool root, string work, params string[] subs)
		{
			return GetDirectory(AppDomain.CurrentDomain, make, root, work, subs);
		}

		/// <summary>
		/// 获取目录，返回 Bin 目录，或 App_Data 目录下的路径；
		/// 此方法不能完全代替 Http 环境下的 HttpServerUtility::MapPath 方法，相对或虚拟目录不能正确转义
		/// </summary>
		/// <param name="make">如果返回路径为目录，创建目录</param>
		/// <param name="root">从 Root 目录中返回路径，如果不存在 Root 目录则返回基准目录下的路径</param>
		/// <param name="work">从进程根目录或基目录下返回主工作(App_Data)目录路径，如果为空(Empty)则返回 App_Data 目录，如果前缀为 ~/ 则返回基准目录下路径</param>
		/// <param name="subs">子目录名列表，如果任意元素的前缀为 ~/ 则返回基准目录下路径</param>
		/// <returns>目录路径</returns>
		public static string GetDirectory(bool make, bool root, string work, params string[] subs)
		{
			return GetDirectory(AppDomain.CurrentDomain, make, root, work, subs);
		}

		/// <summary>
		/// 获取目录，返回 Bin 目录，或 App_Data 目录下的路径；
		/// 此方法不能完全代替 Http 环境下的 HttpServerUtility::MapPath 方法，相对或虚拟目录不能正确转义
		/// </summary>
		/// <param name="root">从 Root 目录中返回路径，如果不存在 Root 目录则返回基准目录下的路径</param>
		/// <param name="work">从进程根目录或基目录下返回主工作(App_Data)目录路径，如果为空(Empty)则返回 App_Data 目录，如果前缀为 ~/ 则返回基准目录下路径</param>
		/// <param name="subs">子目录名列表，如果任意元素的前缀为 ~/ 则返回基准目录下路径</param>
		/// <returns>目录路径</returns>
		public static string GetDirectory(bool root, string work, params string[] subs)
		{
			return GetDirectory(AppDomain.CurrentDomain, true, root, work, subs);
		}

		/// <summary>
		/// 获取目录，返回 Bin 目录，或 App_Data 目录下的路径；
		/// 此方法不能完全代替 Http 环境下的 HttpServerUtility::MapPath 方法，相对或虚拟目录不能正确转义
		/// </summary>
		/// <param name="work">从进程根目录或基目录下返回主工作(App_Data)目录路径，如果为空(Empty)则返回 App_Data 目录，如果前缀为 ~/ 则返回基准目录下路径</param>
		/// <param name="subs">子目录名列表，如果任意元素的前缀为 ~/ 则返回基准目录下路径</param>
		/// <returns>目录路径</returns>
		public static string GetDirectory(string work, params string[] subs)
		{
			return GetDirectory(AppDomain.CurrentDomain, true, false, work, subs);
		}

		/// <summary>
		/// 获取目录，返回 Bin 目录，或 App_Data 目录下的路径；
		/// 此方法不能完全代替 Http 环境下的 HttpServerUtility::MapPath 方法，相对或虚拟目录不能正确转义
		/// </summary>
		/// <param name="work">从进程根目录或基目录下返回主工作(App_Data)目录路径，如果为空(Empty)则返回 App_Data 目录，如果前缀为 ~/ 则返回基准目录下路径</param>
		/// <returns>目录路径</returns>
		public static string GetDirectory(string work)
		{
			return GetDirectory(AppDomain.CurrentDomain, true, false, work, Reflector<string>.NullArray);
		}

		#endregion

		/// <summary>
		/// 取已知通讯类型列表
		/// </summary>
		/// <typeparam name="ATTRIBUTE">属性类型</typeparam>
		/// <param name="provider">属性提供者</param>
		/// <param name="assemblies">从指定程序集中取已知类型</param>
		/// <returns></returns>
		public static IEnumerable<Type> GetKnownTypes<ATTRIBUTE>(this ICustomAttributeProvider provider, params Assembly[] assemblies)
		{
			var ls = new List<Type>();
			var m = provider as MemberInfo;
			if (m != null)
			{
				var t = m.DeclaringType;
				if (t == null)
					t = m as Type;
				if (t != null && !string.IsNullOrEmpty(t.Namespace))
				{
					var ns = t.Namespace.Split('.');
					var ms = AppDomain.CurrentDomain.GetAssemblies();
					foreach (var a in ms)
					{
						var ts = a.GetTypes();
						foreach (var item in ts)
						{
							if (item != null && !string.IsNullOrEmpty(item.Namespace) && item.Namespace.Split('.')[0] == ns[0] && !ls.Contains(item))
								ls.Add(item);
						}
					}
				}
				if (t != null)
				{
					var ts = t.Assembly.GetTypes();
					foreach (var item in ts)
					{
						if (!ls.Contains(item))
							ls.Add(item);
					}
				}
			}
			if (assemblies != null && assemblies.Length > 0)
			{
				foreach (var a in assemblies)
				{
					var ts = a.GetTypes();
					foreach (var item in ts)
					{
						if (!ls.Contains(item))
							ls.Add(item);
					}
				}
			}
			return Reflector.GetKnownTypes<ATTRIBUTE>(ls);
		}

		private static IEnumerable<Type> GetKnownTypes<ATTRIBUTE>(List<Type> types)
		{
			for (var i = 0; i < types.Count; i++)
			{
				var ts = types[i].GetGenericArguments();
				foreach (var t in ts)
				{
					if (types.Contains(t))
						continue;

					types.Add(t);
				}
			}
			for (var i = types.Count - 1; i >= 0; i--)
			{
				var t = types[i];
				while (t != typeof(object) && t.GetCustomAttributes(typeof(ATTRIBUTE), false).Length > 0)
					t = t.BaseType;
				if (typeof(object) != t)//if (types[i].GetCustomAttributes(typeof(ATTRIBUTE), false).Length == 0)//if (types[i].GetCustomAttributes(typeof(ATTRIBUTE), true).Length == 0)
				{
					types.RemoveAt(i);
					continue;
				}

				t = types[i];
				while (t.HasElementType)
					t = t.GetElementType();
				if (t.IsEnum)
					continue;

				var cs = t.GetConstructors(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance);
				foreach (var c in cs)//删除所有未定义无参构造函数的类型。
				{
					if (c.GetParameters().Length == 0)
					{
						t = null;
						cs = null;
						break;
					}
				}
				if (t == null)
					continue;

				types.RemoveAt(i);
			}
			for (var i = 0; i < types.Count; i++)
			{
				if (types[i].IsArray)// || types[i] == t || types[i].IsSubclassOf(t)//var t = typeof(CommunicationException);
					continue;

				if (types[i].IsGenericType)//types[i].IsGenericTypeDefinition
					continue;

				var t = Array.CreateInstance(types[i], 0).GetType();
				types.Add(t);
				t = typeof(FaultException<>);
				t = t.MakeGenericType(types[i]);
				types.Add(t);
				if (t != null)//以下代码永不执行。
					continue;

				#region 排除类别

				if (typeof(NullableBoolean) == types[i])
					continue;

				t = typeof(CDelegateBase);
				if (types[i].IsSubclassOf(t) || types[i] == t)
					continue;

				t = typeof(DelegateAttribute);
				if (types[i].IsSubclassOf(t) || types[i] == t)
					continue;

				#endregion 排除类别

				if (types[i].IsClass)
				{
					t = typeof(EntitySet<>);
					t = t.MakeGenericType(types[i]);
					types.Add(t);
				}
				t = typeof(List<>);
				t = t.MakeGenericType(types[i]);
				types.Add(t);
			}
			for (var i = types.Count - 1; i >= 0; i--)
			{
				if (types[i].IsGenericTypeDefinition)
				{
					if (types[i].GetGenericArguments().Length == 1)
					{
						for (var ii = types.Count - 1; ii >= 0; ii--)
						{
							if (types[ii].IsGenericType || types[ii].IsGenericTypeDefinition)
								continue;

							try
							{
								var t = types[i].MakeGenericType(types[ii]);
								types.Add(t);
							}
							catch { }
						}
					}
					types.RemoveAt(i);
				}
			}

			types.Add(typeof(FaultException));

			//types.Add(typeof(CDelegate));
			//types.Add(typeof(DelegateAttribute));
			//types.Add(typeof(DelegateAttribute[]));

			//if (KnownTypeProvider._Cache == null)
			//	KnownTypeProvider._Cache = new Dictionary<ICustomAttributeProvider, Type[]>();
			//KnownTypeProvider._Cache.Add(knownTypeAttributeTarget, types.ToArray());
			//return KnownTypeProvider._Cache[knownTypeAttributeTarget];

			return types;
		}

		#region Get Method Name

		/// <summary>
		/// 取方法全称，格式：Binding ReturnType {Assembly.FullName}::Type.FullName::Method.Name(ParameterType ParameterName,...)
		/// </summary>
		/// <param name="handler">委托</param>
		/// <returns>方法全称</returns>
		public static string GetMethodShortName(IDelegate handler)
		{
			return Reflector.GetMethodShortName(Reflector.GetMethodFullName(handler.Handler.Method));
		}

		/// <summary>
		/// 取方法全称，格式：Binding ReturnType {Assembly.FullName}::Type.FullName::Method.Name(ParameterType ParameterName,...)
		/// </summary>
		/// <param name="handler">委托</param>
		/// <returns>方法全称</returns>
		public static string GetMethodShortName(Delegate handler)
		{
			return Reflector.GetMethodShortName(Reflector.GetMethodFullName(handler.Method));
		}

		/// <summary>
		/// 取方法全称，格式：Binding ReturnType {Assembly.FullName}::Type.FullName::Method.Name(ParameterType ParameterName,...)
		/// </summary>
		/// <param name="method">方法</param>
		/// <returns>方法全称</returns>
		public static string GetMethodShortName(MethodInfo method)
		{
			return Reflector.GetMethodShortName(Reflector.GetMethodFullName(method));
		}

		/// <summary>
		/// 取方法全称，格式：Type.FullName::Method.Name
		/// </summary>
		/// <param name="fullName">方法全称，格式：Binding ReturnType {Assembly.FullName}::Type.FullName::Method.Name(ParameterType ParameterName,...)</param>
		/// <returns>方法全称</returns>
		public static string GetMethodShortName(string fullName)
		{
			Match match = Regex.Match(fullName, @"([^ \:]+\:\:[^ \:\(\)]+)(\(([^\)]*)\))?$", RegexOptions.Compiled);
			if (match.Success)
				return match.Groups[1].Value;

			return null;
		}

		/// <summary>
		/// 取方法全称，格式：Binding ReturnType {Assembly.FullName}::Type.FullName::Method.Name(ParameterType ParameterName,...)
		/// </summary>
		/// <param name="handler">委托</param>
		/// <returns>方法全称</returns>
		public static string GetMethodFullName(IDelegate handler)
		{
			return GetMethodFullName(handler.Handler.Method);
		}

		/// <summary>
		/// 取方法全称，格式：Binding ReturnType {Assembly.FullName}::Type.FullName::Method.Name(ParameterType ParameterName,...)
		/// </summary>
		/// <param name="handler">委托</param>
		/// <returns>方法全称</returns>
		public static string GetMethodFullName(Delegate handler)
		{
			return GetMethodFullName(handler.Method);
		}

		/// <summary>
		/// 取方法全称，格式：Binding ReturnType {Assembly.FullName}::Type.FullName::Method.Name(ParameterType ParameterName,...)
		/// </summary>
		/// <param name="method">方法</param>
		/// <returns>方法全称</returns>
		public static string GetMethodFullName(MethodInfo method)
		{
			string t = string.Empty;
			ParameterInfo[] ps = method.GetParameters();
			for (int i = 0; i < ps.Length; i++)
			{
				if (i > 0)
					t += ",";
				if (ps[i].IsIn)
					t += "in ";
				if (ps[i].IsOut)
					t += "out ";
				if (ps[i].IsRetval)
					t += "ref ";
				t = t + ps[i].ParameterType.FullName + " " + ps[i].Name;
			}
			//t = string.Format("{0} {{{1}}}::{2}({3})", method.ReturnType, method.DeclaringType.AssemblyQualifiedName, method.Name, t);
			t = string.Format("{0} {{{1}}}::{2}::{3}({4})", method.ReturnType, method.DeclaringType.Assembly.FullName, method.DeclaringType, method.Name, t);
			if (method.IsVirtual)
				t = "virtual " + t;
			if (method.IsStatic)
				t = "static " + t;
			if (method.IsAbstract)
				t = "abstract " + t;
			if (method.IsPublic)
				t = "public " + t;
			else if (method.IsPrivate)
				t = "private " + t;
			else if (method.IsHideBySig)
				t = "internal " + t;
			else// if (method.IsHideBySig)
				t = "protected " + t;
			return t;
		}

		#endregion

		#region get method attribute value:description,display name

		/// <summary>
		/// 取方法描述
		/// </summary>
		/// <param name="fullName">方法全称，格式：{Assembly.FullName}::Type.FullName::Method.Name(ParameterType ParameterName,...)</param>
		/// <returns>方法描述</returns>
		public static string GetMethodDescription(string fullName)
		{
			return GetMethodDescription(GetMethod(fullName));
		}
		/// <summary>
		/// 取方法描述
		/// </summary>
		/// <param name="handler">委托</param>
		/// <returns>方法描述</returns>
		public static string GetMethodDescription(IDelegate handler)
		{
			return GetMethodDescription(handler.Handler.Method);
		}
		/// <summary>
		/// 取方法描述
		/// </summary>
		/// <param name="handler">委托</param>
		/// <returns>方法描述</returns>
		public static string GetMethodDescription(Delegate handler)
		{
			return GetMethodDescription(handler.Method);
		}
		/// <summary>
		/// 取方法描述
		/// </summary>
		/// <param name="method">方法</param>
		/// <returns>方法描述</returns>
		public static string GetMethodDescription(MethodBase method)
		{
			if (method == null)
				return null;

			object[] os = method.GetCustomAttributes(typeof(DescriptionAttribute), true);
			if (os == null || os.Length == 0)
				return null;

			string t = string.Empty;
			for (int i = 0; i < os.Length; i++)
			{
				if (i > 0)
					t += Environment.NewLine;
				t += ((DescriptionAttribute)os[i]).Description;
			}
			return t;
		}

		/// <summary>
		/// 取方法友好名称
		/// </summary>
		/// <param name="fullName">方法全称，格式：{Assembly.FullName}::Type.FullName::Method.Name(ParameterType ParameterName,...)</param>
		/// <returns>友好名称</returns>
		public static string GetMethodDisplayName(string fullName)
		{
			return GetMethodDisplayName(GetMethod(fullName));
		}
		/// <summary>
		/// 取方法友好名称
		/// </summary>
		/// <param name="handler">委托</param>
		/// <returns>友好名称</returns>
		public static string GetMethodDisplayName(IDelegate handler)
		{
			return GetMethodDisplayName(handler.Handler.Method);
		}
		/// <summary>
		/// 取方法友好名称
		/// </summary>
		/// <param name="handler">委托</param>
		/// <returns>友好名称</returns>
		public static string GetMethodDisplayName(Delegate handler)
		{
			return GetMethodDisplayName(handler.Method);
		}
		/// <summary>
		/// 取方法友好名称
		/// </summary>
		/// <param name="method">方法</param>
		/// <returns>友好名称</returns>
		public static string GetMethodDisplayName(MethodBase method)
		{
			if (method == null)
				return null;

			object[] os = method.GetCustomAttributes(typeof(DisplayNameAttribute), true);
			if (os == null || os.Length == 0)
				return null;

			string t = string.Empty;
			for (int i = 0; i < os.Length; i++)
			{
				if (i > 0)
					t += Environment.NewLine;
				t += ((DisplayNameAttribute)os[i]).DisplayName;
			}
			return t;
		}

		#endregion

		#region GetMethod

		/// <summary>
		/// 取方法信息
		/// </summary>
		/// <returns>方法信息</returns>
		public static MethodBase GetMethod()
		{
			var sfs = new StackTrace(true).GetFrames();
			var sf = new StackFrame(true);
			var mb = sf.GetMethod();
			for (var i = 0; i < sfs.Length; i++)
			{
				if (mb.Equals(sfs[i].GetMethod()))
					return sfs[i + 1].GetMethod();
			}
			return mb;
		}

		/// <summary>
		/// 取方法信息
		/// </summary>
		/// <param name="fullName">方法全称，格式：{Assembly.FullName}::Type.FullName::Method.Name(ParameterType ParameterName,...)</param>
		/// <returns>方法信息</returns>
		public static MethodBase GetMethod(string fullName)
		{
			return Reflector.GetMethod(null, fullName);
		}

		/// <summary>
		/// 取方法信息
		/// </summary>
		/// <param name="type">搜索的类型</param>
		/// <param name="fullName">方法全称，格式：{Assembly.FullName}::Type.FullName::Method.Name(ParameterType ParameterName,...)</param>
		/// <returns>方法信息</returns>
		public static MethodBase GetMethod(Type type, string fullName)
		{
			Match match = Regex.Match(fullName, @"(\{([^\{\}]+)\}\:\:)?([^ \:]+)\:\:([^ \:\(\)]+)(\(([^\)]*)\))?$", RegexOptions.Compiled);
			if (!match.Success)
				return null;

			string[] ts = null;
			Type[] types = null;
			try
			{
				if (string.IsNullOrEmpty(match.Groups[5].Value))
					ts = null;
				else if (string.IsNullOrEmpty(match.Groups[6].Value))
					ts = new string[] { };
				else
					ts = match.Groups[6].Value.Split(',');
				if (ts == null)
					types = null;
				else if (ts.Length == 0)
					types = Type.EmptyTypes;
				else
					types = new Type[ts.Length];
				for (int i = 0; ts != null && i < ts.Length; i++)
					types[i] = Type.GetType(Regex.Match(ts[i], @"([^ ]+) [^ ]+$", RegexOptions.Compiled).Groups[1].Value);

				if (type == null)
				{
					if (string.IsNullOrEmpty(match.Groups[2].Value))
						type = Type.GetType(match.Groups[3].Value);
					else
						type = Assembly.Load(match.Groups[2].Value).GetType(match.Groups[3].Value);
					if (type == null)
						return null;
				}

				if (types == null)
					return type.GetMethod(match.Groups[4].Value, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);// | BindingFlags.FlattenHierarchy

				return type.GetMethod(match.Groups[4].Value, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, types, null);// | BindingFlags.FlattenHierarchy
			}
			catch { }

			return null;
		}

		#endregion

		/// <summary>
		/// 反射所有字段，此方法专用于解决自动属性在派生类中无法获取的问题。
		/// </summary>
		/// <param name="type">要反射的类型</param>
		/// <returns>反射的字段</returns>
		public static FieldInfo[] GetAllFields(this Type type)
		{
			if (type == null)
				return null;

			if (Common.StaticCache.GetAllFields != null && Common.StaticCache.GetAllFields.ContainsKey(type))
			{
				var a0 = Common.StaticCache.GetAllFields[type];
				if (a0 == null || a0.Length == 0)
					return a0;

				var a1 = new FieldInfo[a0.Length];
				a0.CopyTo(a1, 0);
				return a1;
			}

			var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
			var fs = GetAllFields(type, flags);
			if (Common.StaticCache.GetAllFields != null)
				Common.StaticCache.GetAllFields[type] = fs;
			return fs;
		}
		/// <summary>
		/// 反射所有字段，此方法专用于解决自动属性在派生类中无法获取的问题。
		/// </summary>
		/// <param name="type">要反射的类型</param>
		/// <param name="flags">一个位屏蔽，由一个或多个指定搜索执行方式的 System.Reflection.BindingFlags 组成。- 或 -零，以返回 null。</param>
		/// <returns>反射的字段</returns>
		public static FieldInfo[] GetAllFields(this Type type, BindingFlags flags)
		{
			var ls = new List<FieldInfo>(type.GetFields(flags));
			var t = type;
			while (t != null)
			{
				var fs = t.GetFields(flags | BindingFlags.DeclaredOnly);
				foreach (var item in fs)
				{
					var f = item; ;
					foreach (var ff in ls)
					{
						if (f.DeclaringType == ff.DeclaringType && f.Name == ff.Name)
						{
							f = null;
							break;
						}
					}
					if (f != null)//if (!ls.Contains(item))
						ls.Add(item);
				}
				t = t.BaseType;
			}
			return ls.ToArray();
		}

		/// <summary>
		/// 反射所有字段，此方法专用于解决自动属性在派生类中无法获取的问题。
		/// </summary>
		/// <param name="type">要反射的类型</param>
		/// <param name="name">字段名</param>
		/// <param name="instance">是否只反射实例成员。</param>
		/// <returns>反射的字段</returns>
		public static FieldInfo GetAllField(this Type type, string name, bool instance)
		{
			var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
			if (instance)
				flags |= BindingFlags.Instance;
			else
				flags |= BindingFlags.Static;
			return GetAllField(type, name, flags);
		}
		/// <summary>
		/// 反射所有字段，此方法专用于解决自动属性在派生类中无法获取的问题。
		/// </summary>
		/// <param name="type">要反射的类型</param>
		/// <param name="name">字段名</param>
		/// <param name="flags">一个位屏蔽，由一个或多个指定搜索执行方式的 System.Reflection.BindingFlags 组成。- 或 -零，以返回 null。</param>
		/// <returns>反射的字段</returns>
		public static FieldInfo GetAllField(this Type type, string name, BindingFlags flags)
		{
			//if (Common.StaticCache.ForGetAllFields != null && Common.StaticCache.ForGetAllFields.ContainsKey(type))
			//{
			//    var fs = Common.StaticCache.ForGetAllFields[type];
			//    foreach(var f 
			//}
			//ToDo: Common.StaticCache.ForGetAllFields ? GetAllField

			while (type != null)
			{
				var f = type.GetField(name, flags);
				if (f != null)
					return f;

				type = type.BaseType;
			}
			return null;
		}

		/// <summary>
		/// 获取资源流，优先获取当前应用程序域下的同名系统文件流。
		/// </summary>
		/// <param name="member">所在程序集资源的任意类成员</param>
		/// <param name="name">流名称</param>
		/// <returns>同名文件流或资源流</returns>
		public static Stream GetManifestResourceStream(this MemberInfo member, string name)
		{
			if (member == null || string.IsNullOrWhiteSpace(name))
				return Stream.Null;


			if (name[0] == AsciiChar.PERIOD)
				name = member.DeclaringType.FullName + AsciiChar.PERIOD + member.Name + name;
			else if (name.IndexOf(AsciiChar.PERIOD) < 0)
				name = member.DeclaringType.FullName + AsciiChar.PERIOD + member.Name + AsciiChar.PERIOD + name;
			return member.DeclaringType.GetManifestResourceStream(name);
		}
		/// <summary>
		/// 获取资源流，优先获取当前应用程序域下的同名系统文件流。
		/// </summary>
		/// <param name="type">所在程序集资源的任意类型</param>
		/// <param name="name">流名称</param>
		/// <returns>同名文件流或资源流</returns>
		public static Stream GetManifestResourceStream(this Type type, string name)
		{
			if (type == null || string.IsNullOrWhiteSpace(name))
				return Stream.Null;

			if (name[0] == AsciiChar.PERIOD)
				name = type.FullName + name;
			else if (name.IndexOf(AsciiChar.PERIOD) < 0)
				name = type.FullName + AsciiChar.PERIOD + name;
			else if (!name.StartsWith(type.Assembly.GetName().Name, StringComparison.OrdinalIgnoreCase))
				name = type.Namespace + AsciiChar.PERIOD + name;
			return type.Assembly.GetManifestResourceStream(name);
		}
		/// <summary>
		/// 获取资源流，优先获取当前应用程序域下的同名系统文件流。
		/// </summary>
		/// <param name="assembly">所在程序集资源的程序集</param>
		/// <param name="name">流名称</param>
		/// <returns>同名文件流或资源流</returns>
		public static Stream GetManifestResourceStream(this Assembly assembly, string name)
		{
			if (assembly == null || string.IsNullOrWhiteSpace(name))
				return Stream.Null;

			var t = assembly.GetName().Name;
			if (!name.StartsWith(t, StringComparison.OrdinalIgnoreCase))
				name = t + AsciiChar.PERIOD + name;
			t = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, name);
			if (File.Exists(t))
				return File.Open(t, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

			t = Path.Combine(Path.GetDirectoryName(assembly.Location), name);
			if (File.Exists(t))
				return File.Open(t, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

			return assembly.GetManifestResourceStream(name);
		}

		#region GetInstance

		/// <summary>
		/// 获取指定类型对象的一个实例
		/// </summary>
		/// <typeparam name="TYPE">从中实例化对象的类型</typeparam>
		/// <returns>指定类型的对象</returns>
		public static TYPE GetInstance<TYPE>()
		{
			return (TYPE)Reflector.GetInstance(typeof(TYPE), null, null);
		}
		/// <summary>
		/// 获取指定类型对象的一个实例
		/// </summary>
		/// <typeparam name="TYPE">从中实例化对象的类型</typeparam>
		/// <param name="args">
		/// 调用的方法或构造函数的参数列表。
		/// 这是一个对象数组，这些对象与要调用的方法或构造函数的参数具有相同的数量、顺序和类型。
		/// 如果没有任何参数，则 parameters 应为 null。
		/// 如果此实例所表示的方法或构造函数采用 ref 参数（在 Visual Basic 中为 ByRef），使用此函数调用该方法或构造函数时，该参数不需要任何特殊属性。
		/// 如果数组中的对象未用值来显式初始化，则该对象将包含该对象类型的默认值。
		/// 对于引用类型的元素，该值为 null。
		/// 对于值类型的元素，该值为 0、0.0 或 false，具体取决于特定的元素类型。
		/// </param>
		/// <returns>指定类型的对象</returns>
		public static TYPE GetInstance<TYPE>(params object[] args)
		{
			return (TYPE)Reflector.GetInstance(typeof(TYPE), args, null);
		}
		/// <summary>
		/// 获取指定类型对象的一个实例
		/// </summary>
		/// <typeparam name="TYPE">从中实例化对象的类型</typeparam>
		/// <param name="attribute">方法属性或构造函数的自定义属性</param>
		/// <returns>指定类型的对象</returns>
		public static TYPE GetInstance<TYPE>(Type attribute)
		{
			return (TYPE)Reflector.GetInstance(typeof(TYPE), null, attribute);
		}
		/// <summary>
		/// 获取指定类型对象的一个实例
		/// </summary>
		/// <typeparam name="TYPE">从中实例化对象的类型</typeparam>
		/// <param name="args">
		/// 调用的方法或构造函数的参数列表。
		/// 这是一个对象数组，这些对象与要调用的方法或构造函数的参数具有相同的数量、顺序和类型。
		/// 如果没有任何参数，则 parameters 应为 null。
		/// 如果此实例所表示的方法或构造函数采用 ref 参数（在 Visual Basic 中为 ByRef），使用此函数调用该方法或构造函数时，该参数不需要任何特殊属性。
		/// 如果数组中的对象未用值来显式初始化，则该对象将包含该对象类型的默认值。
		/// 对于引用类型的元素，该值为 null。
		/// 对于值类型的元素，该值为 0、0.0 或 false，具体取决于特定的元素类型。
		/// </param>
		/// <param name="attribute">方法属性或构造函数的自定义属性</param>
		/// <returns>指定类型的对象</returns>
		public static TYPE GetInstance<TYPE>(object[] args, Type attribute)
		{
			return (TYPE)Reflector.GetInstance(typeof(TYPE), args, attribute);
		}
		/// <summary>
		/// 获取指定类型对象的一个实例
		/// </summary>
		/// <param name="type">从中实例化对象的类型</param>
		/// <returns>指定类型的对象</returns>
		public static object GetInstance(this Type type)
		{
			return Reflector.GetInstance(type, null, null);
		}
		/// <summary>
		/// 获取指定类型对象的一个实例
		/// </summary>
		/// <param name="type">从中实例化对象的类型</param>
		/// <param name="args">
		/// 调用的方法或构造函数的参数列表。
		/// 这是一个对象数组，这些对象与要调用的方法或构造函数的参数具有相同的数量、顺序和类型。
		/// 如果没有任何参数，则 parameters 应为 null。
		/// 如果此实例所表示的方法或构造函数采用 ref 参数（在 Visual Basic 中为 ByRef），使用此函数调用该方法或构造函数时，该参数不需要任何特殊属性。
		/// 如果数组中的对象未用值来显式初始化，则该对象将包含该对象类型的默认值。
		/// 对于引用类型的元素，该值为 null。
		/// 对于值类型的元素，该值为 0、0.0 或 false，具体取决于特定的元素类型。
		/// </param>
		/// <returns>指定类型的对象</returns>
		public static object GetInstance(this Type type, params object[] args)
		{
			return Reflector.GetInstance(type, args, null);
		}
		/// <summary>
		/// 获取指定类型对象的一个实例
		/// </summary>
		/// <param name="type">从中实例化对象的类型</param>
		/// <param name="attribute">方法属性或构造函数的自定义属性</param>
		/// <returns>指定类型的对象</returns>
		public static object GetInstance(this Type type, Type attribute)
		{
			return Reflector.GetInstance(type, null, attribute);
		}
		/// <summary>
		/// 获取指定类型对象的一个实例
		/// </summary>
		/// <param name="type">从中实例化对象的类型</param>
		/// <param name="args">
		/// 调用的方法或构造函数的参数列表。
		/// 这是一个对象数组，这些对象与要调用的方法或构造函数的参数具有相同的数量、顺序和类型。
		/// 如果没有任何参数，则 parameters 应为 null。
		/// 如果此实例所表示的方法或构造函数采用 ref 参数（在 Visual Basic 中为 ByRef），使用此函数调用该方法或构造函数时，该参数不需要任何特殊属性。
		/// 如果数组中的对象未用值来显式初始化，则该对象将包含该对象类型的默认值。
		/// 对于引用类型的元素，该值为 null。
		/// 对于值类型的元素，该值为 0、0.0 或 false，具体取决于特定的元素类型。
		/// </param>
		/// <param name="attribute">方法属性或构造函数的自定义属性</param>
		/// <returns>指定类型的对象</returns>
		public static object GetInstance(this Type type, object[] args, Type attribute)
		{
			int i;
			object[] os;
			if (type == null)
				return null;

			if (type.IsInterface || type.IsValueType || type.IsEnum)
				return null;

			int iArgs = 0;
			if (args != null)
				iArgs = args.Length;
			var ms = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);// | BindingFlags.FlattenHierarchy//MethodInfo
			foreach (var m in ms)
			{
				if (m.ReturnType != type)
					continue;

				if (m.GetParameters().Length != iArgs)
					continue;

				if (attribute != null)
				{
					os = m.GetCustomAttributes(attribute, true);
					if (os.Length == 0)
						continue;

					for (i = 0; i < os.Length; i++)
					{
						if (attribute.Equals(os[i]))
							break;
					}
					if (i >= os.Length)
						continue;
				}

				return m.Invoke(null, args);
			}

			var ps = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);// | BindingFlags.FlattenHierarchy//PropertyInfo
			foreach (var p in ps)
			{
				if (p.PropertyType != type)
					continue;

				if (attribute != null)
				{
					os = p.GetCustomAttributes(attribute, true);
					if (os.Length == 0)
						continue;

					for (i = 0; i < os.Length; i++)
					{
						if (attribute.Equals(os[i]))
							break;
					}
					if (i >= os.Length)
						continue;
				}

				return p.GetValue(null, null);//args
			}

			if (type.IsAbstract)
				return null;

			var cs = type.GetConstructors(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);//ConstructorInfo
			var ls = new List<ConstructorInfo>(cs);
			if (type.TypeInitializer != null)
				ls.Insert(0, type.TypeInitializer);
			foreach (var c in ls)
			{
				if (c.GetParameters().Length != iArgs)
					continue;

				if (attribute != null)
				{
					os = c.GetCustomAttributes(attribute, true);
					if (os.Length == 0)
						continue;

					for (i = 0; i < os.Length; i++)
					{
						if (attribute.Equals(os[i]))
							break;
					}
					if (i >= os.Length)
						continue;
				}

				if ((args != null && args.Length > 0) || c != type.TypeInitializer)
					return c.Invoke(args);

				var m = typeof(Reflector).GetMethod("TypeInitializer", BindingFlags.NonPublic | BindingFlags.Static);
				m = m.MakeGenericMethod(type);
				return m.Invoke(null, null);
			}

			return null;
		}

		/// <summary>
		/// 针对调用构造函数时抛出“不可调用类型初始值设定项”异常而申明实现。
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <returns></returns>
		private static T TypeInitializer<T>() where T : new()
		{
			//TypeInitializer:System.MemberAccessException = 不可调用类型初始值设定项。
			return new T();//System.Reflection.TargetInvocationException = 调用的目标发生了异常。
		}

		#endregion

		#region Serializable

		/// <summary>
		/// 序列化指定的对象
		/// </summary>
		/// <param name="graph">要序列化的对象</param>
		/// <param name="info">要填充数据的 System.Runtime.Serialization.SerializationInfo。</param>
		/// <param name="context">此序列化的目标（请参见 System.Runtime.Serialization.StreamingContext）。</param>
		/// <returns>要序列化的对象</returns>
		public static object Serialize(this object graph, SerializationInfo info, StreamingContext context)
		{
			return Reflector.Serialize(graph, info, context, null, Guid.Empty, false);
		}
		private static object Serialize(object graph, SerializationInfo info, StreamingContext context, Hashtable table, Guid guid, bool ignoreError)
		{
			if (graph == null)
				return null;

			if (guid == Guid.Empty)
				guid = Guid.NewGuid();
			if (info.MemberCount == 0)
				info.AddValue(string.Empty, guid);

			if (table == null)
				table = new Hashtable();
			if (!table.ContainsKey(graph))
				table.Add(graph, guid);

			var generation = 0;
			var type = graph.GetType();
			if (string.IsNullOrEmpty(info.AssemblyName) && string.IsNullOrEmpty(info.FullTypeName))
				info.SetType(type);
			var fs = type.GetAllFields();// type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);// | BindingFlags.DeclaredOnly | BindingFlags.Static);
			var fl = fs.Length;// fs.Length
			while (type != null)
			{
				//var fs = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);// | BindingFlags.Static);
				//foreach (var f in fs)
				for (var fi = 0; fi < fl; fi++)
				{
					var f = fs[fi];
					if (f == null || f.DeclaringType != type)
						continue;

					fs[fi] = null;
					if (f.IsStatic || f.GetCustomAttributes(typeof(NonSerializedAttribute), false).Length != 0)
						continue;

					var value = f.GetValue(graph);
					if (value == null || value == f.FieldType.GetDefault())
						continue;

					var name = generation + "|" + f.Name;
					if (table.ContainsKey(value))
					{
						info.AddValue(name, guid + Environment.NewLine + table[value] + Environment.NewLine + f.FieldType.FullName + Environment.NewLine + f.FieldType.Assembly.FullName);
						continue;
					}

					table.Add(value, name);
					//if (false)//其它类型成员
					//{
					//    var key = Guid.NewGuid();
					//    info.AddValue(name, guid + Environment.NewLine + key + Environment.NewLine + f.FieldType.FullName + Environment.NewLine + f.FieldType.Assembly.FullName);
					//    CReflection.Serialize(value, info, context, table, key, ignoreCase);
					//    continue;
					//}

					info.AddValue(name, value);
				}
				generation++;
				type = type.BaseType;
			}
			return graph;
		}
		/// <summary>
		/// 序列化指定的对象
		/// </summary>
		/// <param name="graph">要序列化的对象</param>
		/// <param name="info">要填充数据的 System.Xml.XmlNode。</param>
		/// <returns>要序列化的对象</returns>
		public static object Serialize(this object graph, XmlNode info)
		{
			return Reflector.Serialize(graph, info, new StreamingContext(StreamingContextStates.All ^ StreamingContextStates.Remoting), null, false);
		}
		/// <summary>
		/// 序列化指定的对象
		/// </summary>
		/// <param name="graph">要序列化的对象</param>
		/// <param name="info">要填充数据的 System.Xml.XmlNode。</param>
		/// <param name="context">此序列化的目标（请参见 System.Runtime.Serialization.StreamingContext）。</param>
		/// <returns>要序列化的对象</returns>
		public static object Serialize(this object graph, XmlNode info, StreamingContext context)
		{
			return Reflector.Serialize(graph, info, context, null, false);
		}
		private static object Serialize(object graph, XmlNode info, StreamingContext context, Hashtable table, bool ignoreError)
		{
			if (graph == null)
				return null;

			var type = graph.GetType();
			var xml = info as XmlDocument;
			if (xml != null && xml.DocumentElement == null)
				info = xml.AppendChild(xml.CreateElement(type.Name));
			if (xml == null)
				xml = info.OwnerDocument;

			if (table == null)
				table = new Hashtable();
			if (!table.ContainsKey(graph))
				table.Add(graph, table.Count);

			var generation = 0;
			if (info.SelectSingleNode("@AssemblyName") == null && info.SelectSingleNode("@FullTypeName") == null)
			{
				info.Attributes.Append(xml.CreateAttribute("AssemblyName")).Value = type.Assembly.FullName;
				info.Attributes.Append(xml.CreateAttribute("FullTypeName")).Value = type.FullName;
			}

			var fs = type.GetAllFields();// type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);// | BindingFlags.DeclaredOnly | BindingFlags.Static);
			var fl = fs.Length;// fs.Length
			while (type != null)
			{
				//var fs = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);// | BindingFlags.Static);
				//foreach (var f in fs)
				for (var fi = 0; fi < fl; fi++)
				{
					var f = fs[fi];
					if (f == null || f.DeclaringType != type)
						continue;

					fs[fi] = null;
					if (f.IsStatic || f.GetCustomAttributes(typeof(NonSerializedAttribute), false).Length != 0)
						continue;

					var value = f.GetValue(graph);
					if (value == null)
						continue;

					var xn = info.AppendChild(xml.CreateElement(f.Name));
					if (generation > 0)
						xn.Attributes.Append(xml.CreateAttribute("Generation")).Value = generation.ToString();
					if (f.FieldType.Assembly != typeof(Type).Assembly)
						xn.Attributes.Append(xml.CreateAttribute("AssemblyName")).Value = f.FieldType.Assembly.FullName;
					xn.Attributes.Append(xml.CreateAttribute("FullTypeName")).Value = f.FieldType.FullName;
					Reflector.SerializeField(value, xn, context, table, ignoreError);
				}
				generation++;
				type = type.BaseType;
			}
			return graph;
		}
		private static object SerializeField(object graph, XmlNode info, StreamingContext context, Hashtable table, bool ignoreError)
		{
			if (graph == null)
				return null;

			if (table.ContainsKey(graph))
			{
				info.InnerText = table[graph].ToString();//ToDo:Serialize
				return graph;
			}

			info.Attributes.Append(info.OwnerDocument.CreateAttribute("Serial")).Value = table.Count.ToString();
			table.Add(graph, table.Count);
			var type = graph.GetType();
			var array = graph as Array;
			if (array != null)
			{
				type = Type.GetType(type.AssemblyQualifiedName.Replace("[]", string.Empty));
				var indices = new long[array.Rank];
				while (true)
				{
					var t = indices[0].ToString();
					for (var i = 1; i < indices.Length; i++)
						t = t + "," + indices[i];
					var value = array.GetValue(indices);
					var xn = info.AppendChild(info.OwnerDocument.CreateElement("Item"));
					xn.Attributes.Append(info.OwnerDocument.CreateAttribute("Indices")).Value = t;
					if (value != null)
					{
						var type0 = value.GetType();
						if (type0 != type)
						{
							if (type0.Assembly != typeof(Type).Assembly)
								xn.Attributes.Append(info.OwnerDocument.CreateAttribute("AssemblyName")).Value = type0.Assembly.FullName;
							xn.Attributes.Append(info.OwnerDocument.CreateAttribute("FullTypeName")).Value = type0.FullName;
						}
						Reflector.SerializeField(value, xn, context, table, ignoreError);
					}
					indices[indices.Length - 1]++;
					for (var i = indices.Length - 1; i >= 0; i--)
					{
						if (array.GetLength(i) > indices[i])
							break;

						if (i == 0)
							return graph;

						indices[i] = 0;
						indices[i - 1]++;
					}
				}
				//return graph;
			}

			//if (false)//其它类型成员
			//{
			//    var key = Guid.NewGuid();
			//    info.InnerText = key.ToString();
			//    CReflection.Serialize(value, info, context, table, key, ignoreCase);
			//    continue;
			//}

			info.InnerText = graph.ToString();//ToDo:Serialize
			return graph;
		}

		/// <summary>
		/// 序列化指定的对象
		/// </summary>
		/// <param name="graph">要序列化的对象</param>
		/// <param name="stream">存储对象的流，如果为空则创建一个内存流对象</param>
		/// <returns>存储对象的流</returns>
		public static Stream Serialize(this object graph, Stream stream)
		{
			if (graph == null)
				return null;

			if (stream == null)
				stream = new MemoryStream();
			var type = graph.GetType();
			var te = type;
			if (te.IsArray && typeof(byte[]) != te)
			{
				var array = graph as Array;
				var os = new object[array.Length];
				array.CopyTo(os, 0);
				for (var i = 0; i < os.Length; i++)
				{
					if (os[i] != null)
					{
						te = os[i].GetType();
						break;
					}
				}
			}
			var ss = te.GetCustomAttributes(typeof(SerializableAttribute), false);
			//if (te.BaseType != null &&
			//    te.BaseType != typeof(object) &&
			//    te.BaseType != typeof(MarshalByRefObject) &&
			//    ss != null &&
			//    ss.Length > 0)
			//{
			//    var sss = te.BaseType.GetCustomAttributes(typeof(SerializableAttribute), false);
			//    if (sss != null && sss.Length == 0)//sss.Length == ss.Length
			//        ss = null;
			//}
			if (te == typeof(object) ||
				te == typeof(MarshalByRefObject) ||
				graph is Array ||
				graph is ISerializable ||
				graph is IMethodCallMessage ||
				graph is IMethodReturnMessage ||
				(ss != null && ss.Length > 0))
			{
				var bf = new BinaryFormatter();//(null, new StreamingContext(StreamingContextStates.All ^ StreamingContextStates.Remoting));
				bf.Serialize(stream, graph);
				return stream;
			}

			ss = te.GetCustomAttributes(typeof(DataContractAttribute), false);
			if (te.BaseType != null && ss != null && ss.Length > 0)
			{
				var sss = te.BaseType.GetCustomAttributes(typeof(DataContractAttribute), false);
				if (sss != null && sss.Length == ss.Length)
					ss = null;
			}
			if (graph is IXmlSerializable || (ss != null && ss.Length > 0))
			{
				var dcs = new DataContractSerializer(type, Common.StaticCache.KnownTypes);
				dcs.WriteObject(stream, graph);
				var t = string.Format("<!--\r\n{1}\r\n{0}\r\n-->", type.AssemblyQualifiedName, dcs.GetType().AssemblyQualifiedName);
				t = t + string.Format("<!-- {0:0000000} -->", t.Length);
				var bs = Encoding.UTF8.GetBytes(t);
				stream.Write(bs, 0, bs.Length);
			}
			else
			{
				var xs = new XmlSerializer(type, Common.StaticCache.KnownTypes);
				xs.Serialize(stream, graph);
				var t = string.Format("<!--\r\n{1}\r\n{0}\r\n-->", type.AssemblyQualifiedName, xs.GetType().AssemblyQualifiedName);
				t = t + string.Format("<!-- {0:0000000} -->", t.Length);
				var bs = Encoding.UTF8.GetBytes(t);
				stream.Write(bs, 0, bs.Length);
			}
			return stream;
		}

		/// <summary>
		/// Data Contract Serialize
		/// </summary>
		/// <param name="graph">要序列化的对象</param>
		/// <param name="type">对象类型。</param>
		/// <returns>序列化内容。</returns>
		public static StringBuilder DataContractSerialize(this object graph, Type type)
		{
			var sb = new StringBuilder();
			var xw = XmlWriter.Create(sb);
			Reflector.DataContractSerialize(graph, xw, type);
			xw.Close();
			return sb;
		}
		private static void DataContractSerialize(object graph, XmlWriter writer, Type type)
		{
			var dcs = new DataContractSerializer(type, Common.StaticCache.KnownTypes);
			dcs.WriteObject(writer, graph);
			var t = string.Format("<!--\r\n{1}\r\n{0}\r\n-->", type.AssemblyQualifiedName, dcs.GetType().AssemblyQualifiedName);
			t = t + string.Format("<!-- {0:0000000} -->", t.Length);
			writer.WriteRaw(t);
		}

		/// <summary>
		/// Xml Serialize
		/// </summary>
		/// <param name="graph">要序列化的对象</param>
		/// <param name="type">对象类型。</param>
		/// <returns>序列化内容。</returns>
		public static StringBuilder XmlSerialize(this object graph, Type type)
		{
			var sb = new StringBuilder();
			var xw = XmlWriter.Create(sb);
			Reflector.XmlSerialize(graph, xw, type);
			xw.Close();
			return sb;
		}
		private static void XmlSerialize(this object graph, XmlWriter writer, Type type)
		{
			var xs = new XmlSerializer(type, Common.StaticCache.KnownTypes);
			xs.Serialize(writer, graph);
			var t = string.Format("<!--\r\n{1}\r\n{0}\r\n-->", type.AssemblyQualifiedName, xs.GetType().AssemblyQualifiedName);
			t = t + string.Format("<!-- {0:0000000} -->", t.Length);
			writer.WriteRaw(t);
		}

		/// <summary>
		/// 反序列化指定的对象
		/// </summary>
		/// <param name="graph">要反序列化的对象</param>
		/// <param name="info">要填充数据的 System.Runtime.Serialization.SerializationInfo。</param>
		/// <param name="context">此序列化的目标（请参见 System.Runtime.Serialization.StreamingContext）。</param>
		/// <returns>要反序列化的对象</returns>
		public static object Deserialize(this object graph, SerializationInfo info, StreamingContext context)
		{
			if (graph == null || info.MemberCount == 0)
				return null;

			var i = 0;
			var type = graph.GetType();
			var guid = info.GetValue(string.Empty, typeof(Guid)) + string.Empty;
			var fs = type.GetAllFields();// type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);// | BindingFlags.DeclaredOnly | BindingFlags.Static);
			var fl = fs.Length; //fs.Count; //
			while (type != null)
			{
				//var fs = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);// | BindingFlags.Static);
				//foreach (var f in fs)
				for (var fi = 0; fi < fl; fi++)
				{
					var f = fs[fi];
					if (f == null || f.DeclaringType != type)
						continue;

					fs[fi] = null;
					if (f.IsStatic)
						continue;

					var name = i + "|" + f.Name;
					try
					{
						var t = info.GetValue(name, typeof(string)) as string;
						var ts = t.Split(new char[] { '\r', '\n', '\t', '\v' }, StringSplitOptions.RemoveEmptyEntries);
						if (ts[0] != guid || f.FieldType.FullName != ts[2])
							throw new Exception();

						if (ts[1] == guid)
						{
							f.SetValue(graph, graph);
							continue;
						}

						var value = info.GetValue(ts[1], f.FieldType);
						f.SetValue(graph, value);
						continue;
					}
					catch (InvalidCastException x)
					{
						Tracker.WriteError(x);
					}
					catch (Exception x)
					{
						Tracker.WriteError(x);
						//f.SetValue(@object, null);
						continue;
					}

					f.SetValue(graph, info.GetValue(name, f.FieldType));
				}
				i++;
				type = type.BaseType;
			}
			return graph;
		}

		/// <summary>
		/// 反序列化对象
		/// </summary>
		/// <param name="data">存储对象的流</param>
		/// <returns>反序列化后的对象</returns>
		public static object Deserialize(this Stream data)
		{
			if (data == null)
				return null;

			if (!data.CanSeek)
			{
				var bf = new BinaryFormatter();
				return bf.Deserialize(data);
			}

			if (data.Length == 0)
				return null;

			var position = data.Position;
			if (data.ReadByte() != (int)'<')
			{
				data.Position = position;
				var bf = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.All ^ StreamingContextStates.Remoting));
				return bf.Deserialize(data);
			}

			var bs = new byte[16];
			data.Position = data.Length - bs.Length;
			data.Read(bs, 0, bs.Length);
			var t = Encoding.UTF8.GetString(bs);
			if (!t.StartsWith("<!-- ") || !t.EndsWith(" -->"))
				return null;

			var i = Regex.Replace(t, "[^0-9]+", string.Empty, RegexOptions.Compiled).ToInt32(0);
			if (i == 0 || i + bs.Length > data.Length)
				return null;

			data.Position = data.Length - bs.Length - i;
			bs = new byte[i];
			data.Read(bs, 0, bs.Length);
			t = Encoding.UTF8.GetString(bs);
			var ts = t.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
			if (ts.Length <= 1)
				return null;

			var dst = Type.GetType(ts[1], false, false);
			if (dst == null)
				return null;

			var type = Type.GetType(ts[ts.Length - 2], false, false);
			if (type == null)
				return null;

			data.Position = position;
			if (typeof(DataContractSerializer) == dst)
			{
				var dcs = new DataContractSerializer(type, Common.StaticCache.KnownTypes);
				return dcs.ReadObject(data);
			}

			if (typeof(XmlSerializer) == dst)
			{
				var xs = new XmlSerializer(type, Common.StaticCache.KnownTypes);
				return xs.Deserialize(data);
			}

			return null;
		}

		/// <summary>
		/// 反序列化对象
		/// </summary>
		/// <param name="data">存储对象的流</param>
		/// <returns>反序列化后的对象</returns>
		public static object Deserialize(this byte[] data)
		{
			if (data == null || data.Length == 0)
				return null;

			var s = new MemoryStream(data);
			var o = Reflector.Deserialize(s);
			s.Close();
			s.Dispose();
			return o;
		}

		#endregion

		#region GetGuidAttributeValue

		/// <summary>
		/// 获取类的 GuidAttribute::Value 值。
		/// </summary>
		/// <param name="provider">自定义属性提供者。</param>
		/// <returns>类的 GuidAttribute::Value 值。</returns>
		public static Guid GetGuidAttributeValue(this ICustomAttributeProvider provider)
		{
			if (provider == null)
				provider = typeof(Reflector).Assembly;
			var gs = provider.GetCustomAttributes(typeof(GuidAttribute), true) as GuidAttribute[];
			if (gs == null || gs.Length == 0)
				return Guid.Empty;

			try
			{
				return new Guid(gs[0].Value);
			}
			catch
			{
				return Guid.Empty;
			}
		}
		/// <summary>
		/// 获取类程序集的 GuidAttribute::Value 值。
		/// </summary>
		/// <param name="type">程序集中的任何类型。</param>
		/// <returns>类程序集的 GuidAttribute::Value 值。</returns>
		public static Guid GetAssemblyGuidAttributeValue(this Type type)
		{
			if (type == null)
				type = typeof(Reflector);
			return type.Assembly.GetGuidAttributeValue();
		}
		/// <summary>
		/// 获取类程序集的 GuidAttribute::Value 值。
		/// </summary>
		/// <param name="assembly">程序集中的任何类型。</param>
		/// <returns>类程序集的 GuidAttribute::Value 值。</returns>
		public static Guid GetAssemblyGuidAttributeValue(this Assembly assembly)
		{
			if (assembly == null)
				assembly = typeof(Reflector).Assembly;
			return assembly.GetGuidAttributeValue();
		}

		#endregion

		private static Dictionary<Type, object> TypeDefaultValues;

		/// <summary>
		/// 获取指定委托类型的空体委托
		/// </summary>
		/// <typeparam name="T">委托类型</typeparam>
		/// <returns>指定委托类型的空体委托</returns>
		public static T GetHandler<T>()
		{
			var t = typeof(T);
			if (t.BaseType != typeof(MulticastDelegate))
				return default(T);

			var m = t.GetMethod(new Func<T>(new Func<T>(GetHandler<T>).Invoke).Method.Name);
			var ps = m.GetParameters();
			var rp = m.ReturnType;
			var es = new ParameterExpression[ps.Length];
			for (var i = 0; i < es.Length; i++)
				es[i] = Expression.Parameter(ps[i].ParameterType, ps[i].Name);
			if (rp == Void)
			{
				var vt = Expression.Label();
				var vl = Expression.Label(vt);
				var vr = Expression.Return(vt);
				var vb = Expression.Block(vr, vl);
				var vm = Expression.Lambda<T>(vb, es);
				var vc = vm.Compile();
				return vc;
			}

			var et = Expression.Label(rp);
			var el = Expression.Label(et, Expression.Default(rp));
			var er = Expression.Return(et, Expression.Default(rp));
			var eb = Expression.Block(er, el);
			var em = Expression.Lambda<T>(eb, es);
			var ec = em.Compile();
			return ec;
		}

		/// <summary>
		/// 获取指定委托类型的空体委托
		/// </summary>
		/// <param name="handler">委托类型</param>
		/// <returns>指定委托类型的空体委托</returns>
		public static Delegate GetHandler(Type handler)
		{
			var h = new Func<Action>(GetHandler<Action>);
			var mg = h.Method.GetGenericMethodDefinition();
			var mi = mg.MakeGenericMethod(handler);
			var hv = mi.Invoke(null, null);
			return hv as Delegate;
		}

		/// <summary>
		/// 获取指定类型的默认对象实例。
		/// </summary>
		/// <param name="type">指定的类型。</param>
		/// <returns>指定类型的默认对象实例。</returns>
		public static object GetDefault(this Type type)
		{
			if (type == null || type.IsClass || type == Reflector.Void)
				return null;

			if (type.IsEnum)
				return byte.MinValue;

			if (TypeDefaultValues != null && TypeDefaultValues.ContainsKey(type))
				return TypeDefaultValues[type];

			var method = GetDefault<bool>(true) as MethodInfo;
			method = method.GetGenericMethodDefinition();
			method = method.MakeGenericMethod(type);
			var value = method.Invoke(null, new object[] { false });
			if (TypeDefaultValues == null)
				TypeDefaultValues = new Dictionary<Type, object>();
			TypeDefaultValues[type] = value;
			return value;
		}

		private static object GetDefault<TYPE>(bool test)
		{
			if (test)
				return MethodBase.GetCurrentMethod();

			return default(TYPE);
		}

		/// <summary>
		/// 判断是否为指定类型的默认对象实例。
		/// </summary>
		/// <param name="type">指定的类型。</param>
		/// <param name="value">要判断的值。</param>
		/// <returns>是否为指定类型的默认对象实例。</returns>
		public static bool IsDefault(this Type type, object value)
		{
			if (type.IsClass)// || type == Reflector.Void)
			{
				if (value == null)
					return true;

				return false;
			}

			if (type.IsEnum)
			{
				if (object.Equals(value, byte.MinValue))
					return true;

				return false;
			}

			var v = value;
			IsDefault<bool>(true, ref v);
			var method = v as MethodInfo;
			method = method.GetGenericMethodDefinition();
			method = method.MakeGenericMethod(type);
			v = method.Invoke(null, new object[] { false });
			return (bool)v;
		}

		private static bool IsDefault<TYPE>(bool test, ref object value)
		{
			if (test)
				value = MethodBase.GetCurrentMethod();
			return object.Equals(value, default(TYPE));
		}

		/// <summary>
		/// 判断指定的对象是否为指定类型或其派生类型的实例。
		/// </summary>
		/// <param name="instance">指定的对象</param>
		/// <param name="type">指定的类型。</param>
		/// <returns>是否为指定类型或其派生类型的实例。</returns>
		public static bool IsType(this object instance, string type)
		{
			var t = Type.GetType(type, false, false);
			if (t != null)
				return instance.IsType(t);

			if (instance == null)
				return false;

			var it = instance.GetType();
			t = it.GetInterface(type);
			if (t != null)
				return true;

			var ts = it.GetInterfaces();
			foreach (var tt in ts)
			{
				if (tt.FullName == type || tt.Name == type)
					return true;
			}

			while (it != null)
			{
				if (it.FullName == type || it.Name == type)
					return true;

				it = it.BaseType;
			}

			return false;
		}

		/// <summary>
		/// 判断指定的对象是否为指定类型或其派生类型的实例。
		/// </summary>
		/// <param name="instance">指定的对象</param>
		/// <param name="type">指定的类型。</param>
		/// <returns>是否为指定类型或其派生类型的实例。</returns>
		public static bool IsType(this object instance, Type type)
		{
			var t = instance as Type;
			if (t != null)
			{
				if (t == type)
					return true;

				return t.IsSubclassOf(type);
			}

			if (type == Reflector.Void)
			{
				if (instance == null)
					return true;

				return false;
			}

			if (instance == null)
				return false;

			var method = IsType<bool>(instance, true) as MethodInfo;
			method = method.GetGenericMethodDefinition();
			method = method.MakeGenericMethod(type);
			return (bool)method.Invoke(null, new object[] { instance, false });
		}

		private static object IsType<TYPE>(object instance, bool test)
		{
			if (test)
				return MethodBase.GetCurrentMethod();

			return (instance is TYPE);
		}

		private static bool TryParseEnum<E>(string value, ref object result) where E : struct
		{
			var e = default(E);
			var v = Enum.TryParse<E>(value, out e);
			if (v)
			{
				result = e;
				return v;
			}

			if (result is E)
				return v;

			if (result != null)
				result = e;
			return v;
		}
		private static bool TryParseEnum<E>(string value, bool ignoreCase, ref object result) where E : struct
		{
			var e = default(E);
			var v = Enum.TryParse<E>(value, ignoreCase, out e);
			if (v)
			{
				result = e;
				return v;
			}

			if (result is E)
				return v;

			if (result != null)
				result = e;
			return v;
		}
		/// <summary>
		/// 将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。一个参数指定该操作是否区分大小写。用于指示转换是否成功的返回值。
		/// </summary>
		/// <param name="enumType">要将 value 转换为的枚举类型。</param>
		/// <param name="value">要转换的枚举名称或基础值的字符串表示形式。</param>
		/// <param name="result">此方法在返回时包含一个类型为 TEnum 的一个对象，其值由 value 表示。该参数未经初始化即被传递。</param>
		/// <returns>如果 value 参数成功转换，则为 true；否则为 false。</returns>
		/// <exception cref="System.ArgumentException">enumType 不是枚举类型。</exception>
		public static bool TryParseEnum(Type enumType, string value, out object result)
		{
			if (enumType == null)
				throw new ArgumentNullException(MethodBase.GetCurrentMethod().GetParameters()[0].Name);

			if (!enumType.IsEnum)
				throw new ArgumentException("不是枚举类型", MethodBase.GetCurrentMethod().GetParameters()[0].Name);

			var h = new TryRefHandler<bool, string, object>(TryParseEnum<TypeCode>);
			var m = h.Method.GetGenericMethodDefinition();
			m = m.MakeGenericMethod(enumType);
			h = Delegate.CreateDelegate(typeof(TryRefHandler<bool, string, object>), m) as TryRefHandler<bool, string, object>;
			result = enumType;
			return h(value, ref result);
		}
		/// <summary>
		/// 将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。一个参数指定该操作是否区分大小写。用于指示转换是否成功的返回值。
		/// </summary>
		/// <param name="enumType">要将 value 转换为的枚举类型。</param>
		/// <param name="value">要转换的枚举名称或基础值的字符串表示形式。</param>
		/// <param name="ignoreCase">true 表示不区分大小写；false 表示区分大小写。</param>
		/// <param name="result">此方法在返回时包含一个类型为 TEnum 的一个对象，其值由 value 表示。该参数未经初始化即被传递。</param>
		/// <returns>如果 value 参数成功转换，则为 true；否则为 false。</returns>
		/// <exception cref="System.ArgumentException">enumType 不是枚举类型。</exception>
		public static bool TryParseEnum(Type enumType, string value, bool ignoreCase, out object result)
		{
			if (enumType == null)
				throw new ArgumentNullException(MethodBase.GetCurrentMethod().GetParameters()[0].Name);

			if(!enumType.IsEnum)
				throw new ArgumentException("不是枚举类型", MethodBase.GetCurrentMethod().GetParameters()[0].Name);

			var h = new TryRefHandler<bool, string, bool, object>(TryParseEnum<TypeCode>);
			var m = h.Method.GetGenericMethodDefinition();
			m = m.MakeGenericMethod(enumType);
			h = Delegate.CreateDelegate(typeof(TryRefHandler<bool, string, bool, object>), m) as TryRefHandler<bool, string, bool, object>;
			result = enumType;
			return h(value, ignoreCase, ref result);
		}
		/// <summary>
		/// 将基本类型转换为指定的枚举类型
		/// </summary>
		/// <param name="value">传入的数据</param>
		/// <param name="enumType">枚举类型</param>
		/// <returns>枚举类型数据</returns>
		public static object EnumFromUnderlying(object value, Type enumType)
		{
			/*
<?xml version="1.0"?>
<doc>
    <assembly>
        <name>PickGold</name>
    </assembly>
    <members>
        <member name="F:PickGold.EPeriod.OneYear">
            <summary>
            当前时间往前一年
            </summary>
        </member>
    </members>
</doc>
			*/
			if (enumType == null || !enumType.IsEnum)
				return value;

			if (value == null)
				return enumType.GetDefault();

			var ut = Enum.GetUnderlyingType(enumType);
			var vt = value.GetType();
			if (vt != ut)
			{
				if (vt == enumType)
					return value;

				var v = value + string.Empty;
				if (string.IsNullOrWhiteSpace(v))
					return value;

				var e = value;
				var h = new TryRefHandler<bool, string, object>(TryParseEnum<TypeCode>);
				var m = h.Method.GetGenericMethodDefinition();
				m = m.MakeGenericMethod(enumType);
				h = Delegate.CreateDelegate(typeof(TryRefHandler<bool, string, object>), m) as TryRefHandler<bool, string, object>;
				if (h(v, ref e))
					return e;

				if (v[0] < '0' || v[1] > '9')
					return value;

				switch (Type.GetTypeCode(vt))
				{
					case TypeCode.Byte:
						var ub = byte.MinValue;
						if (!byte.TryParse(v, out ub))
							return value;

						value = ub;
						break;
					case TypeCode.SByte:
						var nb = sbyte.MinValue;
						if (!sbyte.TryParse(v, out nb))
							return value;

						value = nb;
						break;
					case TypeCode.Int16:
						var us = short.MinValue;
						if (!short.TryParse(v, out us))
							return value;

						value = us;
						break;
					case TypeCode.UInt16:
						var ns = ushort.MinValue;
						if (!ushort.TryParse(v, out ns))
							return value;

						value = ns;
						break;
					case TypeCode.Int32:
						var ui = int.MinValue;
						if (!int.TryParse(v, out ui))
							return value;

						value = ui;
						break;
					case TypeCode.UInt32:
						var ni = uint.MinValue;
						if (!uint.TryParse(v, out ni))
							return value;

						value = ni;
						break;
					case TypeCode.Int64:
						var ul = long.MinValue;
						if (!long.TryParse(v, out ul))
							return value;

						value = ul;
						break;
					case TypeCode.UInt64:
						var nl = ulong.MinValue;
						if (!ulong.TryParse(v, out nl))
							return value;

						value = nl;
						break;
					default:
						return value;
				}
			}

			if (!Monitor.TryEnter(Common.StaticCache.EnumFromUnderlying, Fiber.LockTimeout))
				Fiber.ThrowLockTimeoutException(Common.StaticCache.EnumFromUnderlying);
			try
			{
				if (Common.StaticCache.EnumFromUnderlying.ContainsKey(enumType))
					return Common.StaticCache.EnumFromUnderlying[enumType](value);
			}
			finally
			{
				Monitor.Exit(Common.StaticCache.EnumFromUnderlying);
			}

			var pi = Expression.Parameter(typeof(object), "i");
			var vu = Expression.Variable(Enum.GetUnderlyingType(enumType), "u");
			var ve = Expression.Variable(enumType, "e");
			var vo = Expression.Variable(pi.Type, "o");
			var ei = Expression.Assign(vu, Expression.Convert(pi, vu.Type));
			var eu = Expression.Assign(ve, Expression.Convert(vu, ve.Type));
			var eo = Expression.Assign(vo, Expression.Convert(ve, pi.Type));
			var lt = Expression.Label(pi.Type, "r");
			var er = Expression.Return(lt, vo, pi.Type);
			var b = Expression.Block(new ParameterExpression[] { vu, ve, vo, }, ei, eu, eo, er, Expression.Label(lt, pi));
			var l = Expression.Lambda<Func<object, object>>(b, pi);
			var d = l.Compile();
			if (!Monitor.TryEnter(Common.StaticCache.EnumFromUnderlying, Fiber.LockTimeout))
				Fiber.ThrowLockTimeoutException(Common.StaticCache.EnumFromUnderlying);
			try
			{
				Common.StaticCache.EnumFromUnderlying[enumType] = d;
			}
			finally
			{
				Monitor.Exit(Common.StaticCache.EnumFromUnderlying);
			}
			value = d(value);
			return value;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="value"></param>
		/// <param name="data"></param>
		/// <param name="spliter"></param>
		/// <returns></returns>
		public static string Title(this Enum value, object data = null, string spliter = null)
		{
			var cache = Common.StaticCache.ForEnumTitle;
			var type = value.GetType();
			var key = data as string;
			var xml = new XmlDocument();
			var doc = xml;
			if (key != null)//输入字符串
			{
				if (string.IsNullOrWhiteSpace(key))
				{
					key = value.ToString();
				}
				else
				{
					var v = Reflector.EnumFromUnderlying(key.Replace('|', ','), type);
					if (v == null || v is string)//字符串不可转换为枚举
						cache = null;
					else
						value = (Enum)v;//字符串可转换为枚举
				}
			}
			else if (data != null && data != DBNull.Value)
			{
				var v = Reflector.EnumFromUnderlying(data, type);
				if (v == null || v is string)
					return data + string.Empty;

				value = (Enum)v;
			}

			var fs = type.GetCustomAttributes(typeof(FlagsAttribute), true);
			if (fs == null || fs.Length == 0)
			{
				if (cache != null)
				{
					if (!Monitor.TryEnter(cache, Fiber.LockTimeout))
						Fiber.ThrowLockTimeoutException(cache);
					try
					{
						if (cache.ContainsKey(value))
							return cache[value];
					}
					finally
					{
						Monitor.Exit(cache);
					}
				}

				var xf = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
				xf = Path.Combine(Path.GetDirectoryName(xf), typeof(Enum).Name + Path.GetExtension(xf));
				if (File.Exists(xf))
				{
					try
					{
						xml.Load(xf);
					}
					catch (Exception x)
					{
						x.SetLastError();
						return x.Message;
					}
				}
				else
				{
					xml = null;
				}
				if (key == null)
					key = value + string.Empty;
				if (xml != null && xml.DocumentElement != null)//ToDo:此判断多余
					key = EnumTitle(type, key, xml, ref doc) ?? EnumTitle(type, key);
				else
					key = EnumTitle(type, key);
				if (cache != null)
				{
					if (!Monitor.TryEnter(cache, Fiber.LockTimeout))
						Fiber.ThrowLockTimeoutException(cache);
					try
					{
						cache[value] = key;
					}
					finally
					{
						Monitor.Exit(cache);
					}
				}
				return key;
			}

			var tc = Type.GetTypeCode(Enum.GetUnderlyingType(type));
			var ev = tc == TypeCode.Int64 ? ulong.Parse(((Enum)value).ToString("X"), NumberStyles.HexNumber) : Convert.ToUInt64(value);
			key = null;
			if (string.IsNullOrWhiteSpace(spliter))
				spliter = " | ";
			foreach (var v in Enum.GetValues(type))
			{
				var vl = tc == TypeCode.Int64 ? ulong.Parse(((Enum)v).ToString("X"), NumberStyles.HexNumber) : Convert.ToUInt64(v);
				if (vl == 0UL || (ev & vl) != vl)
					continue;

				if (cache != null)
				{
					if (!Monitor.TryEnter(cache, Fiber.LockTimeout))
						Fiber.ThrowLockTimeoutException(cache);
					try
					{
						if (cache.ContainsKey((Enum)v))
						{
							if (key == null)
								key = cache[(Enum)v];
							else
								key = key + spliter + cache[(Enum)v];
							continue;
						}
					}
					finally
					{
						Monitor.Exit(cache);
					}
				}

				var t = v + string.Empty;
				if (xml != null && xml.DocumentElement == null)
				{
					var xf = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
					xf = Path.Combine(Path.GetDirectoryName(xf), typeof(Enum).Name + Path.GetExtension(xf));
					if (File.Exists(xf))
					{
						try
						{
							xml.Load(xf);
						}
						catch (Exception x)
						{
							x.SetLastError();
							return x.Message;
						}
					}
					else
					{
						xml = null;
					}
				}
				if (xml != null && xml.DocumentElement != null)
					t = EnumTitle(type, t, xml, ref doc) ?? EnumTitle(type, t);
				else
					t = EnumTitle(type, t);
				if (cache != null)
				{
					if (!Monitor.TryEnter(cache, Fiber.LockTimeout))
						Fiber.ThrowLockTimeoutException(cache);
					try
					{
						cache[(Enum)v] = t;
					}
					finally
					{
						Monitor.Exit(cache);
					}
				}
				if (key == null)
					key = t;
				else
					key = key + spliter + t;
				//ev ^= vl;
			}
			if (key == null)
				key = value + string.Empty;
			return key;
		}
		private static string EnumTitle(Type type, string key, XmlDocument xml, ref XmlDocument doc)
		{
			if (xml == null || xml.DocumentElement == null)
			{
				if (doc == null)
					return null;

				if (doc == xml || doc.DocumentElement == null || doc.SelectSingleNode("//assembly") == null)
				{
					var fn = type.Assembly.GetName().Name + ".xml";//Mime.XML;
					var xf = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fn);
					if (!File.Exists(xf))
					{
						xf = Path.Combine(AppDomain.CurrentDomain.RelativeSearchPath, fn);
						if (!File.Exists(xf))
						{
							if (string.IsNullOrWhiteSpace(AppDomain.CurrentDomain.SetupInformation.PrivateBinPath) || AppDomain.CurrentDomain.SetupInformation.PrivateBinPath == AppDomain.CurrentDomain.RelativeSearchPath)
							{
								doc = null;
								return null;
							}

							xf = Path.Combine(AppDomain.CurrentDomain.RelativeSearchPath, fn);
							if (!File.Exists(xf))
							{
								doc = null;
								return null;
							}
						}
					}

					doc = new XmlDocument();
					try
					{
						doc.Load(xf);
						if (doc.DocumentElement == null || doc.SelectSingleNode("//assembly") == null)
						{
							doc = null;
							return null;
						}
					}
					catch (Exception x)
					{
						x.SetLastError();
						doc = null;
						return null;
					}
				}
				var n = doc.SelectSingleNode("//member[@name='F:" + type.FullName.Replace('+', '.') + "." + key + "']");
				if (n != null && !string.IsNullOrWhiteSpace(n.InnerText))
					return Regex.Replace(n.InnerText, @"^[\r\n\t\s ]+|[\r\n\t\s ]+$", string.Empty, RegexOptions.Compiled | RegexOptions.Multiline);

				return null;
			}

			var xn = xml.FirstChild;
			try
			{
				xn = xn.SelectSingleNode("//" + type.Name + "/" + key);// <Enum><value title=?>
			}
			catch (Exception x)
			{
				Tracker.LastError = x;
				return key;
			}

			if (xn == null)
			{
				xn = xml.DocumentElement.SelectSingleNode("//" + type.Name + "[@key='" + key + "']");// <Enum key=value title=?>
				if (xn == null)
					xn = xml.DocumentElement.SelectSingleNode("//" + type.Name + "/*[@key='" + key + "']");// <Enum><* key=value title=?>
			}
			if (xn == null)
			{
				if (doc != null)
					return EnumTitle(type, key, null, ref doc);

				return null;
			}

			for (var i = xn.Attributes.Count - 1; i >= 0; i--)
			{
				var xa = xn.Attributes[i];
				if (xa != null && (string.Compare(xa.Name, "title", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(xa.Name, "value", StringComparison.OrdinalIgnoreCase) == 0))
				{
					if (string.IsNullOrWhiteSpace(xa.Value))
						return key;

					return xa.Value;
				}
			}

			if (string.IsNullOrWhiteSpace(xn.InnerText))
				return key;

			return xn.InnerText;
		}
		private static string EnumTitle(Type type, string key)
		{
			var f = type.GetField(key);
			if (f == null)
				return key;

			var cs = f.GetCustomAttributes(typeof(DisplayNameAttribute), true);
			if (cs != null && cs.Length > 0)
			{
				var dn = cs[0] as DisplayNameAttribute;
				if (dn != null && !string.IsNullOrWhiteSpace(dn.DisplayName))
					return dn.DisplayName;
			}

			cs = f.GetCustomAttributes(typeof(DescriptionAttribute), true);
			if (cs != null && cs.Length > 0)
			{
				var dn = cs[0] as DescriptionAttribute;
				if (dn != null && !string.IsNullOrWhiteSpace(dn.Description))
					return dn.Description;
			}

			return key;
		}

		/// <summary>
		/// 取成员
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <typeparam name="V"></typeparam>
		/// <param name="instance"></param>
		/// <param name="member"></param>
		/// <returns></returns>
		public static MemberInfo Member<T, V>(this T instance, Expression<Func<T, V>> member)
		{
			if (member == null || member.Body == null)
				throw new ArgumentNullException(MethodBase.GetCurrentMethod().GetParameters()[0].Name);

			var e = member.Body as MemberExpression;
			if (e == null)
				throw new ArgumentException("Must be member accessor.", MethodBase.GetCurrentMethod().GetParameters()[0].Name);

			return e.Member;
		}
		/// <summary>
		/// 取成员名
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <typeparam name="V"></typeparam>
		/// <param name="instance"></param>
		/// <param name="member"></param>
		/// <returns></returns>
		public static string MemberName<T, V>(this T instance, Expression<Func<T, V>> member)
		{
			if (member == null || member.Body == null)
				throw new ArgumentNullException(MethodBase.GetCurrentMethod().GetParameters()[0].Name);

			var e = member.Body as MemberExpression;
			if (e == null || e.Member == null)
				throw new ArgumentException("Must be member accessor.", MethodBase.GetCurrentMethod().GetParameters()[0].Name);

			return e.Member.Name;
		}

		/// <summary>
		/// 创建使用从零开始的索引、具有指定 System.Type 和长度的一维 System.Array。
		/// </summary>
		/// <param name="type">要创建的 System.Array 的 System.Type。</param>
		/// <param name="length">要创建的 System.Array 的大小。</param>
		/// <returns>使用从零开始的索引、具有指定 System.Type 和指定长度的新的一维 System.Array。</returns>
		/// <exception cref="System.ArgumentNullException">type 为 null。</exception>
		/// <exception cref="System.ArgumentException">type 不是有效的 System.Type。</exception>
		/// <exception cref="System.NotSupportedException">type 不受支持。例如，不支持 System.Void。- 或 -type 是一个开放式泛型类型。</exception>
		/// <exception cref="System.ArgumentOutOfRangeException">length 小于零。</exception>
		public static Array MakeArray(this Type type, int length = 0)
		{
			var method = MakeArray<bool>(int.MinValue) as MethodInfo;
			method = method.GetGenericMethodDefinition();
			method = method.MakeGenericMethod(type);
			return method.Invoke(null, new object[] { length }) as Array;
		}
		/// <summary>
		/// 创建使用从零开始的索引、具有指定 T 和长度的一维数组。
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="graph">要创建的数组的对象。</param>
		/// <param name="length">要创建的数组的大小。</param>
		/// <returns></returns>
		public static T[] MakeArray<T>(this T graph, int length = 0)
		{
			if (length > 0)
			{
				var os = new T[length];
				os[0] = graph;
				return os;
			}

			if (length == 0)
				return Reflector<T>.EmptyArray;

			return Reflector<T>.NullArray;
		}
		private static object MakeArray<T>(int length)
		{
			if (length >= 0)
				return new T[length];

			return MethodBase.GetCurrentMethod();
		}

		/// <summary>
		/// 构造类型实例
		/// </summary>
		/// <typeparam name="G">
		/// 要构造类型或改变的泛类型；
		/// 如果 types 未传入：直接构造此类型实例并返回；
		/// 如果类型是泛类型：按传入 types 的参数改变泛类型定义并构造新类型实例并返回；
		/// 如果类型不是泛类型：返回传入 types 的参数类型的实例数组；
		/// </typeparam>
		/// <param name="types">构造新泛类型的类型参数数组或需要构造实例的参数数组</param>
		/// <returns></returns>
		public static object NewInstance<G>(params Type[] types) where G : new()
		{
			var t = typeof(G);
			if (t.IsGenericType)
			{
				if (types != null && types.Length > 0)
				{
					var tl = types.Length;
					var td = t.GetGenericTypeDefinition();
					var ps = t.GetGenericArguments();
					var gm = MethodBase.GetCurrentMethod() as MethodInfo;
					for (var i = ps.Length - 1; i >= 0; i--)
					{
						if (i > tl || types[i] == null)
							continue;

						ps[i] = types[i];
					}
					t = td.MakeGenericType(ps);
					gm = gm.GetGenericMethodDefinition();
					return gm.MakeGenericMethod(t).Invoke(null, new object[] { null, });
				}

				return new G();
			}

			if (types != null && types.Length > 0)
			{
				var tl = types.Length;
				var os = new object[tl];
				var gm = MethodBase.GetCurrentMethod() as MethodInfo;
				gm = gm.GetGenericMethodDefinition();
				for (var i = os.Length - 1; i >= 0; i--)
				{
					if (types[i] == null || types[i].IsInterface || types[i].IsAbstract || types[i].IsGenericTypeDefinition)
						continue;

					os[i] = gm.MakeGenericMethod(types[i]).Invoke(null, new object[] { null, });
				}
				if (tl == 1)
					return os[0];

				return os;
			}

			return new G();
		}

		/// <summary>
		/// 创建使用从零开始的索引、具有指定 System.Type 和长度的一维 System.Array。
		/// </summary>
		/// <param name="type">要创建的 System.Array 的 System.Type。</param>
		/// <param name="length">要创建的 System.Array 的大小。</param>
		/// <returns>使用从零开始的索引、具有指定 System.Type 和指定长度的新的一维 System.Array。</returns>
		/// <exception cref="System.ArgumentNullException">type 为 null。</exception>
		/// <exception cref="System.ArgumentException">type 不是有效的 System.Type。</exception>
		/// <exception cref="System.NotSupportedException">type 不受支持。例如，不支持 System.Void。- 或 -type 是一个开放式泛型类型。</exception>
		/// <exception cref="System.ArgumentOutOfRangeException">length 小于零。</exception>
		public static Array CreateArrayInstance(this Type type, int length)
		{
			return Array.CreateInstance(type, length);
		}
		/// <summary>
		/// 创建使用从零开始的索引、具有指定 System.Type 和维长的多维 System.Array。维的长度在一个 32 位整数数组中指定。
		/// </summary>
		/// <param name="type">要创建的 System.Array 的 System.Type。</param>
		/// <param name="lengths">一个 32 位整数数组，它表示要创建的 System.Array 中每个维的大小。</param>
		/// <returns>使用从零开始的索引、具有指定 System.Type 的新的多维 System.Array，其每个维度都为指定的长度。</returns>
		/// <exception cref="System.ArgumentNullException">type 为 null。- 或 -lengths 为 null。</exception>
		/// <exception cref="System.ArgumentException">type 不是有效的 System.Type。- 或 -lengths 数组包含的元素少于一个。</exception>
		/// <exception cref="System.NotSupportedException">type 不受支持。例如，不支持 System.Void。- 或 -type 是一个开放式泛型类型。</exception>
		/// <exception cref="System.ArgumentOutOfRangeException">lengths 中的任何值都小于零。</exception>
		public static Array CreateArrayInstance(this Type type, params int[] lengths)
		{
			return Array.CreateInstance(type, lengths);
		}
		/// <summary>
		/// 创建使用从零开始的索引、具有指定 System.Type 和维长的多维 System.Array。维的长度在一个 64 位整数数组中指定。
		/// </summary>
		/// <param name="type">要创建的 System.Array 的 System.Type。</param>
		/// <param name="lengths">一个 64 位整数数组，它表示要创建的 System.Array 中每个维的大小。数组中的每个整数都必须介于零和 System.Int32.MaxValue 之间，（包括零和 System.Int32.MaxValue）。</param>
		/// <returns>使用从零开始的索引、具有指定 System.Type 的新的多维 System.Array，其每个维度都为指定的长度。</returns>
		/// <exception cref="System.ArgumentNullException">type 为 null。- 或 -lengths 为 null。</exception>
		/// <exception cref="System.ArgumentException">type 不是有效的 System.Type。- 或 -lengths 数组包含的元素少于一个。</exception>
		/// <exception cref="System.NotSupportedException">type 不受支持。例如，不支持 System.Void。- 或 -type 是一个开放式泛型类型。</exception>
		/// <exception cref="System.ArgumentOutOfRangeException">lengths 中的所有值都小于零或大于 System.Int32.MaxValue。</exception>
		public static Array CreateArrayInstance(this Type type, params long[] lengths)
		{
			return Array.CreateInstance(type, lengths);
		}
		/// <summary>
		/// 创建使用从零开始的索引、具有指定 System.Type 和维长的二维 System.Array。
		/// </summary>
		/// <param name="type">要创建的 System.Array 的 System.Type。</param>
		/// <param name="length1">要创建的 System.Array 的第一维的大小。</param>
		/// <param name="length2">要创建的 System.Array 的第二维的大小。</param>
		/// <returns>使用从零开始的索引、具有指定 System.Type 的新的二维 System.Array，其每个维度都为指定的长度。</returns>
		/// <exception cref="System.ArgumentNullException">type 为 null。</exception>
		/// <exception cref="System.ArgumentException">type 不是有效的 System.Type。</exception>
		/// <exception cref="System.NotSupportedException">type 不受支持。例如，不支持 System.Void。- 或 -type 是一个开放式泛型类型。</exception>
		/// <exception cref="System.ArgumentOutOfRangeException">length1 小于零。- 或 -length2 小于零。</exception>
		public static Array CreateArrayInstance(this Type type, int length1, int length2)
		{
			return Array.CreateInstance(type, length1, length2);
		}
		/// <summary>
		/// 创建具有指定下限、指定 System.Type 和维长的多维 System.Array。
		/// </summary>
		/// <param name="type">要创建的 System.Array 的 System.Type。</param>
		/// <param name="lengths">一维数组，它包含要创建的 System.Array 的每个维度的大小。</param>
		/// <param name="lowerBounds">一维数组，它包含要创建的 System.Array 的每个维度的下限（起始索引）。</param>
		/// <returns>新的指定 System.Type 的多维 System.Array，每个维度都有指定的长度和下限。</returns>
		/// <exception cref="System.ArgumentNullException">type 为 null。- 或 -lengths 为 null。- 或 -lowerBounds 为 null。</exception>
		/// <exception cref="System.ArgumentException">type 不是有效的 System.Type。- 或 -lengths 数组包含的元素少于一个。- 或 -lengths 和 lowerBounds 数组包含的元素数不同。</exception>
		/// <exception cref="System.NotSupportedException">type 不受支持。例如，不支持 System.Void。- 或 -type 是一个开放式泛型类型。</exception>
		/// <exception cref="System.ArgumentOutOfRangeException">lengths 中的任何值都小于零。- 或 -lowerBounds 中的任意一个值都很大，因此，维的下限和长度的和大于 System.Int32.MaxValue。</exception>
		public static Array CreateArrayInstance(this Type type, int[] lengths, int[] lowerBounds)
		{
			return Array.CreateInstance(type, lengths, lowerBounds);
		}
		/// <summary>
		/// 创建使用从零开始的索引、具有指定 System.Type 和维长的三维 System.Array。
		/// </summary>
		/// <param name="type">要创建的 System.Array 的 System.Type。</param>
		/// <param name="length1">要创建的 System.Array 的第一维的大小。</param>
		/// <param name="length2">要创建的 System.Array 的第二维的大小。</param>
		/// <param name="length3">要创建的 System.Array 的第三维的大小。</param>
		/// <returns>使用从零开始的索引、具有指定 System.Type 的新的三维 System.Array，每个维度都为指定的长度。</returns>
		/// <exception cref="System.ArgumentNullException">type 为 null。</exception>
		/// <exception cref="System.ArgumentException">type 不是有效的 System.Type。</exception>
		/// <exception cref="System.NotSupportedException">type 不受支持。例如，不支持 System.Void。- 或 -type 是一个开放式泛型类型。</exception>
		/// <exception cref="System.ArgumentOutOfRangeException">length1 小于零。- 或 -length2 小于零。- 或 -length3 小于零。</exception>
		public static Array CreateArrayInstance(this Type type, int length1, int length2, int length3)
		{
			return Array.CreateInstance(type, length1, length2, length3);
		}
		/// <summary/>
		[EditorBrowsable(EditorBrowsableState.Advanced)]
		public static unsafe Array CreateArrayInstance(void* type, int rank, int* pLengths, int* pLowerBounds)
		{
			return InternalCreate(type, rank, pLengths, pLowerBounds);
		}
		[MethodImpl(MethodImplOptions.InternalCall)]
		private static extern unsafe Array InternalCreate(void* elementType, int rank, int* pLengths, int* pLowerBounds);

		/// <summary>
		/// 深层复制对象
		/// </summary>
		/// <param name="graph">要复制的对象</param>
		/// <returns>复制后的新对象</returns>
		public static object Clone(this object graph)
		{
			if (graph == null)
				return null;

			var ms = new MemoryStream();
			var bf = new BinaryFormatter();
			bf.Serialize(ms, graph);
			ms.Position = 0;
			graph = bf.Deserialize(ms);
			bf = null;
			ms.Close();
			ms.Dispose();
			ms = null;
			return graph;
		}

		/// <summary>
		/// 深层复制对象
		/// </summary>
		/// <typeparam name="TYPE">对象的类型</typeparam>
		/// <param name="graph">要复制的对象</param>
		/// <returns>复制后的新对象</returns>
		public static TYPE Clone<TYPE>(this TYPE graph)
		{
			var o = Reflector.Clone(graph);
			if (o != null && o is TYPE)
				return (TYPE)o;

			return default(TYPE);
		}

		/// <summary>
		/// 将源对象的公有成员或属性复制到目标对象中。
		/// </summary>
		/// <typeparam name="TYPE"></typeparam>
		/// <param name="graph"></param>
		/// <param name="target"></param>
		/// <returns></returns>
		public static TYPE FillTo<TYPE>(this TYPE graph, TYPE target)
		{
			var t = typeof(TYPE);
			if (!Common.StaticCache.FillTo.ContainsKey(t))
			{
				var eps = Expression.Parameter(t, "o");
				var ept = Expression.Parameter(t, "t");
				var erl = Expression.Label(t);
				var eba = new List<Expression>();
				var ps = t.GetProperties();
				var fs = t.GetFields();
				foreach (var p in ps)
				{
					var ns = p.GetIndexParameters();
					if (ns != null && ns.Length > 0)
						continue;

					var m = p.GetGetMethod();
					if (m == null || m.IsStatic)
						continue;

					m = p.GetSetMethod();
					if (m == null || m.IsStatic)
						continue;

					eba.Add(Expression.Assign(Expression.Property(ept, p), Expression.Property(eps, p)));
				}
				foreach (var f in fs)
				{
					if (f.IsStatic)
						continue;

					eba.Add(Expression.Assign(Expression.Field(ept, f), Expression.Field(eps, f)));
				}
				eba.Add(Expression.Return(erl, ept));
				eba.Add(Expression.Label(erl, ept));
				var ebb = Expression.Block(eba);
				var el = Expression.Lambda<Func<TYPE, TYPE, TYPE>>(ebb, eps, ept);
				var d = el.Compile();
				Common.StaticCache.FillTo[t] = d;
			}
			var h = Common.StaticCache.FillTo[t] as Func<TYPE, TYPE, TYPE>;
			return h(graph, target);
		}

		/// <summary>
		/// 使用指定的参数调用当前实例所表示的方法或构造函数。
		/// </summary>
		/// <param name="this">对其调用方法或构造函数的对象。如果方法是静态的，则此参数为类型。</param>
		/// <param name="method">要调用的方法名称</param>
		/// <param name="ignoreCase">是否忽略 method 参数的大小写。</param>
		/// <param name="ignoreError">是否忽略错误，如果为非空值则表示忽略错误，当调用出错时则返回此参数值或异常对象；否则将抛出异常。</param>
		/// <param name="params">调用的方法或构造函数的参数列表。这是一个对象数组，这些对象与要调用的方法或构造函数的参数具有相同的数量、顺序和类型。如果没有任何参数，则 parameters 应为 null。如果此实例所表示的方法或构造函数采用 ref 参数（在 Visual Basic 中为 ByRef），使用此函数调用该方法或构造函数时，该参数不需要任何特殊属性。如果数组中的对象未用值来显式初始化，则该对象将包含该对象类型的默认值。对于引用类型的元素，该值为 null。对于值类型的元素，该值为 0、0.0 或 false，具体取决于特定的元素类型。</param>
		/// <returns>一个对象，包含被调用方法的返回值，如果调用的是构造函数，则为 null。如果发生错误，则返回 ignoreError 参数值或异常对象</returns>
		public static object Invoke(this object @this, string method, bool ignoreCase, object ignoreError, params object[] @params)
		{
			if (ignoreError != null && (@this == null || string.IsNullOrEmpty(method)))
				return ignoreError;

			var bf = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;// | BindingFlags.FlattenHierarchy;
			var type = @this as Type;
			if (type == null)
			{
				type = @this.GetType();
				bf |= BindingFlags.Instance;
			}
			if (ignoreCase)
				bf |= BindingFlags.IgnoreCase;
			var mi = type.GetMethod(method, bf);
			if (ignoreError != null && mi == null)
				return ignoreError;

			try
			{
				if (mi.IsStatic)
					ignoreError = mi.Invoke(null, @params);
				else
					ignoreError = mi.Invoke(@this, @params);
			}
			catch (Exception x)
			{
				Tracker.WriteError(x);
				if (ignoreError == null)
					throw;

				ignoreError = x;
			}
			return ignoreError;
		}

		/// <summary>
		/// 返回此成员上定义的自定义属性的数组（由类型标识），如果该类型没有自定义属性，则返回空数组。
		/// </summary>
		/// <param name="member">成员</param>
		/// <param name="attributeType">自定义属性的类型。</param>
		/// <returns>表示自定义属性的对象的数组或空数组。</returns>
		public static IEnumerable<Attribute> GetCustomAttributes(this MemberInfo member, Type attributeType)
		{
			return CustomAttributeExtensions.GetCustomAttributes(member, attributeType);
		}

		/// <summary>
		/// Returns an array of custom attributes defined on this member, identified
		/// by type, or an empty array if there are no custom attributes of that type.
		/// </summary>
		/// <typeparam name="ATTRIBUTE">The type of the custom attributes.</typeparam>
		/// <param name="provider">provider</param>
		/// <param name="inherit">When true, look up the hierarchy chain for the inherited custom attribute.</param>
		/// <returns>An array of Objects representing custom attributes, or an empty array.</returns>
		public static ATTRIBUTE[] GetCustomAttributes<ATTRIBUTE>(this ICustomAttributeProvider provider, bool inherit) where ATTRIBUTE : Attribute
		{
			return provider.GetCustomAttributes(typeof(ATTRIBUTE), inherit) as ATTRIBUTE[];
		}
	}

	/// <summary>
	/// 泛型常用类型值
	/// </summary>
	public class Reflector<TYPE>
	{
		#region class _InfiniteEnumerable : IEnumerable<T>, IEnumerator<T>, IEnumerable, IEnumerator

		class _InfiniteEnumerable : IEnumerable<TYPE>, IEnumerator<TYPE>, IEnumerable, IEnumerator
		{
			object IEnumerator.Current
			{
				get
				{
					return Reflector<TYPE>.DefaultValue;
				}
			}

			bool IEnumerator.MoveNext()
			{
				return true;
			}

			void IEnumerator.Reset()
			{
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return this;
			}

			TYPE IEnumerator<TYPE>.Current
			{
				get
				{
					return Reflector<TYPE>.DefaultValue;
				}
			}

			void IDisposable.Dispose()
			{
			}

			IEnumerator<TYPE> IEnumerable<TYPE>.GetEnumerator()
			{
				return this;
			}
		}

		#endregion

		/// <summary/>
		protected Reflector()
		{
			if (this.GetType() != typeof(Reflector<TYPE>))
				throw new NotSupportedException();
		}

		/// <summary>
		/// 可读写类型值
		/// </summary>
		public static TYPE Value;

		/// <summary>
		/// 可读写类型数组
		/// </summary>
		public static TYPE[] Values;

		/// <summary>
		/// 全局安全线程锁对象
		/// </summary>
		//public readonly static object Synchronized = new object();

		/// <summary>
		/// 类型，只读
		/// </summary>
		public readonly static Type Type = typeof(TYPE);

		/// <summary>
		/// 默认类型值，只读
		/// </summary>
		public readonly static TYPE DefaultValue = default(TYPE);

		/// <summary>
		/// 空体委托
		/// </summary>
		public readonly static TYPE EmptyHandler = Reflector.GetHandler<TYPE>();

		/// <summary>
		/// 空指针类型数组对象，只读
		/// </summary>
		public readonly static TYPE[] NullArray = null;

		/// <summary/>
		public readonly static IList<TYPE> NullListI = null;
		/// <summary/>
		public readonly static List<TYPE> NullList = null;
		/// <summary/>
		public readonly static Queue<TYPE> NullQueue = null;
		/// <summary/>
		public readonly static Stack<TYPE> NullStack = null;
		/// <summary/>
		public readonly static HashSet<TYPE> NullHash = null;
		/// <summary/>
		public readonly static LinkedList<TYPE> NullLink = null;
		/// <summary/>
		public readonly static IQueryable<TYPE> NullQueryable = null;
		/// <summary/>
		public readonly static Expression<TYPE> NullExpression = null;
		/// <summary/>
		public readonly static ReadOnlyCollection<TYPE> NullReadOnly = null;

		/// <summary>
		/// 零长度类型数组对象，只读
		/// </summary>
		public readonly static TYPE[] EmptyArray = new TYPE[] { };

		/// <summary>
		/// 无限枚举器，可直接造成无限循环，使用应极小心
		/// </summary>
		public readonly static IEnumerable<TYPE> InfiniteEnumerable = new _InfiniteEnumerable();
		/// <summary/>
		public static IEnumerable<TYPE> EmptyEnumerable
		{
			get
			{
				return EmptyArray;
			}
		}
		/// <summary/>
		public readonly static ReadOnlyCollection<TYPE> EmptyReadOnly = new ReadOnlyCollection<TYPE>(new List<TYPE>());
	}

	/// <summary>
	/// 泛型常用类型值
	/// </summary>
	public class Reflector<KEY, VALUE> : Reflector<KEY>
	{
		/// <summary/>
		protected Reflector() { }

		/// <summary/>
		public readonly static IDictionary<KEY, VALUE> NullDictionaryI = null;
		/// <summary/>
		public readonly static Dictionary<KEY, VALUE> NullDictionary = null;
		/// <summary/>
		public readonly static SortedDictionary<KEY, VALUE> NullSortedDictionary = null;
		/// <summary/>
		public readonly static SortedList<KEY, VALUE> NullSortedList = null;
	}

	/// <summary>
	/// map path
	/// </summary>
	/// <param name="path">virtual path</param>
	/// <returns></returns>
	public delegate string MapPath(string path);
}
